如何在python中动态创建类变量

38 投票
7 回答
45167 浏览
提问于 2025-04-17 07:18

我需要创建一堆类变量,想通过循环一个列表来实现,像这样:

vars=('tx','ty','tz') #plus plenty more

class Foo():
    for v in vars:
        setattr(no_idea_what_should_go_here,v,0)

这样做可以吗?我不想为某个实例创建这些变量(也就是在 __init__ 里用 self),而是想作为类变量来创建。

7 个回答

9

如果因为某种原因你不能使用Raymond的建议,也就是在类创建后再设置它们,那么你可以考虑使用元类:

class MetaFoo(type):
    def __new__(mcs, classname, bases, dictionary):
        for name in dictionary.get('_extra_vars', ()):
            dictionary[name] = 0
        return type.__new__(mcs, classname, bases, dictionary)

class Foo(): # For python 3.x use 'class Foo(metaclass=MetaFoo):'
    __metaclass__=MetaFoo # For Python 2.x only
    _extra_vars = 'tx ty tz'.split()
10

虽然我来得有点晚,但可以使用type类构造函数

Foo = type("Foo", (), {k: 0 for k in ("tx", "ty", "tz")})
62

你可以在创建一个类之后,立刻运行插入代码:

class Foo():
     ...

vars=('tx', 'ty', 'tz')  # plus plenty more
for v in vars:
    setattr(Foo, v, 0)

另外,你也可以在创建类的过程中,动态地存储变量:

class Bar:
    locals()['tx'] = 'texas'

撰写回答