how to create class variable dynamically in python

前端 未结 4 1869
再見小時候
再見小時候 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:02

    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'
    

提交回复
热议问题