how to create class variable dynamically in python

前端 未结 4 1879
再見小時候
再見小時候 2021-01-31 18: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         


        
4条回答
  •  悲&欢浪女
    2021-01-31 18:52

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

提交回复
热议问题