动态创建类实例的最有效方法是什么? [英] What is the most efficient way to dynamically create class instances?

查看:62
本文介绍了动态创建类实例的最有效方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一开始我不知道会有多少个类实例,所以我需要动态创建它们,但是我也想保持代码整洁和可读。

I don't know how many class instances I will have from the get-go, so I need to create them dynamically, but I would also like to keep the code tidy and readable.

我正在考虑做这样的事情:

I was thinking of doing something like this:

names = ['Jon','Bob','Mary']

class Person():
    def __init__(self, name):
        self.name = name

people = {}
for name in names:
    people[name] = Person(name)

它有效,但是我似乎找不到任何人在网上进行此操作的示例(尽管我看起来并不多)。有什么理由我应该避免这样做吗?如果是这样,为什么以及什么是更好的替代方法?

It works, but I can't seem to find any examples of people doing this online (though I didn't look much). Is there any reason I should avoid doing this? If so, why and what is a better alternative?

推荐答案

如果要动态创建类实例,这正是您所需要的。是在您的代码中执行的,那么我认为您的解决方案看起来非常好,并且是执行此操作的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 :-)

这篇关于动态创建类实例的最有效方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆