how to create class variable dynamically in python

时间秒杀一切 提交于 2019-12-31 08:58:12

问题


I need to make a bunch of class variables and I would like to do it by looping through a list like that:

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

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

is it possible? I don't want to make them for an instance (using self in the __init__) but as class variables.


回答1:


You can run the insertion code immediately after a class is created:

class Foo():
     ...

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

Also, you can dynamically store the variable while the class is being created:

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



回答2:


If for any reason you can't use Raymond's answer of setting them up after the class creation then perhaps you could use a metaclass:

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()



回答3:


Late to the party but use the type class constructor!

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



回答4:


The locals() version did not work for me in a class.

The following can be used to dynamically create the attributes of the class:

class namePerson:
    def __init__(self, value):
        exec("self.{} = '{}'".format("name", value)

me = namePerson(value='my name')
me.name # returns 'my name'


来源:https://stackoverflow.com/questions/8307612/how-to-create-class-variable-dynamically-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!