Setting a class attribute with a given name in python while defining the class

前端 未结 4 1478
南旧
南旧 2021-02-02 16:48

I am trying to do something like this:

property = \'name\'
value = Thing()
class A:
  setattr(A, property, value)
  other_thing = \'normal attribute\'

  def __i         


        
4条回答
  •  一个人的身影
    2021-02-02 17:33

    You can do it even simpler:

    class A():
        vars()['key'] = 'value'
    

    In contrast to the previous answer, this solution plays well with external metaclasses (for ex., Django models).

提交回复
热议问题