how to create class variable dynamically in python

前端 未结 4 1881
再見小時候
再見小時候 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 19:15

    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'
    

提交回复
热议问题