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

paw*_*wel 19 python class class-variables

我需要制作一堆类变量,我想通过循环遍历这样的列表来实现:

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

class Foo():
    for v in vars:
        setattr(no_idea_what_should_go_here,v,0)
Run Code Online (Sandbox Code Playgroud)

可能吗?我不想让它们成为一个实例(在__init__中使用self),而是作为类变量.

Ray*_*ger 36

您可以在创建类后立即运行插入代码:

class Foo():
     ...

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

此外,您可以在创建类时动态存储变量:

class Bar:
    locals()['tx'] = 'texas'
Run Code Online (Sandbox Code Playgroud)


Dun*_*can 7

如果出于任何原因你不能使用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()
Run Code Online (Sandbox Code Playgroud)


cos*_*ouc 6

晚到派对但使用type类构造函数!

Foo = type("Foo", (), {k: 0 for k in ("tx", "ty", "tz")})
Run Code Online (Sandbox Code Playgroud)