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

前端 未结 4 1416
南旧
南旧 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:23

    This may be because the class A is not fully initialized when you do your setattr(A, p, v) there.

    The first thing to try would be to just move the settattr down to after you close the class block and see if that works, e.g.

    class A(object):
        pass

    setattr(A, property, value)

    Otherwise, that thing Ignacio just said about metaclasses.

提交回复
热议问题