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

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

    So I know this is really old and probably beating a dead horse and this may not have been possible at the time but I cam across this trying to solve my own problem.

    I realized this can be accomplished without metaclassing.

    The setattr takes and object, accessor name, and value. Well the object is not the class name it's the specific instance of the class, which can be accomplished with self.

    class A(object):
        def __init__(self):
            self.a = 'i am a accessor'
            setattr(self, 'key', 'value')
    
    a = A()
    print a.a
    print a.key
    

提交回复
热议问题