how to create class variable dynamically in python how to create class variable dynamically in python python python

how to create class variable dynamically in python


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

class Foo():     ...vars=('tx', 'ty', 'tz')  # plus plenty morefor 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'


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


Late to the party but use the type class constructor!

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