python类动态对象实例化创建

问题描述 投票:0回答:1

我想创建一些用户,只是为了填充我的数据库,所以使用装饰器,我在一个类里面为它创建了一个方法。我把结果返回到一个列表中,并顺利使用这些信息。但是过了一段时间,我想,一旦我用类来工作,使用列表岂不是很笨?我觉得我有点倒退了,因为至少在我的理解中,可能可以直接访问这些值。但事实是,我在尝试动态实例化并访问这些实例时,很费劲。那么,我如何才能正确地做到这一点呢?这是我第一次尝试时写的代码。

class User:
    def __init__(self, user_name, password, email, i=0):
        self.user_name = user_name
        self.password = password
        self.email = email

    @classmethod
    def from_generate(cls, amount):
        user_name = 'user' + str(amount)
        password = 'password000.' + str(amount)
        email = 'user' + str(amount) + "@whatever.com"
        return cls(user_name, password, email)

在另一个文件中

def user_generator(user_qty=0):
    user_list = []

    for i in range(1, user_qty + 1):

        # call the class method to generate users
        instance = User.from_generate(i)
        user_list.append(instance)
    return(user_list)



users = user_generator(5)

if __name__ == "__user_generator__":
    user_generator()
python python-3.x class instantiation python-decorators
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.