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

前端 未结 4 1425
南旧
南旧 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

    You'll need to use a metaclass for this:

    property = 'foo'
    value = 'bar'
    
    class MC(type):
      def __init__(cls, name, bases, dict):
        setattr(cls, property, value)
        super(MC, cls).__init__(name, bases, dict)
    
    class C(object):
      __metaclass__ = MC
    
    print C.foo
    

提交回复
热议问题