且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

动态创建类实例的最有效方法是什么?

更新时间:2023-02-09 17:01:36

如果要动态创建类实例,这正是您所需要的。是在您的代码中执行的,那么我认为您的解决方案看起来非常好,并且是执行此操作的Python方法(尽管我必须说当然还有其他方法)。只是为了给您一些思考:您可以使用这样的类注册/存储每个新实例:

If you want to create class instances dynamically, which is exactly what you are doing in your code, then I think your solution looks perfectly fine and is a pythonic way to do so (although I have to say there are of course other ways). Just to give you some food for thought: you could register/store each new instance with the class like that:

class Person():
    people={}
    @classmethod
    def create(cls,name):
        person=Person(name)
        cls.people[name]=person
        return person
    def __init__(self, name):
        self.name = name

如果您喜欢冒险,可以尝试使用元类,但是我将其留给您研究:-)

And if you are getting adventerous, you can try the same with metaclass, but I will leave that for your research :-)