4

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

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

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

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

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

它有效,但我似乎找不到任何人在网上这样做的例子(尽管我看起来并不多)。有什么理由我应该避免这样做吗?如果是这样,为什么以及什么是更好的选择?

4

3 回答 3

5

如果您想动态创建类实例,这正是您在代码中所做的,那么我认为您的解决方案看起来非常好,并且是一种 Python 方式(尽管我不得不说当然还有其他方式)。只是为了给您一些思考:您可以像这样在类中注册/存储每个新实例:

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

如果你喜欢冒险,你可以尝试使用元类,但我会把它留给你的研究 :-)

于 2012-10-01T13:49:51.497 回答
3

Use type(name, bases, dict)

From documentation:

Return a new type object. This is essentially a dynamic form of the class statement. The name string is the class name and becomes the name attribute; the bases tuple itemizes the base classes and becomes the bases attribute; and the dict dictionary is the namespace containing definitions for class body and becomes the dict attribute. For example, the following two statements create identical type objects:

>>> class X(object):
...     a = 1
...
>>> X = type('X', (object,), dict(a=1))

For your example:

>>> JonClass = type('JonClass', (object,), {'name': 'Jon'})
>>> jon_instance = JonClass()
>>> jon_instance.name
'Jon'
>>> type(jon_instance)
<class '__main__.JonClass'>
于 2012-10-01T13:31:32.440 回答
1

使用生成器表达式创建字典怎么样?

people = dict((name, Person(name)) for name in names)

但除此之外,您的解决方案是完全有效的。

于 2012-10-01T14:05:09.447 回答