如何在__init__中定义属性

pki*_*kit 5 python constructor properties

我想从成员函数中定义类中的属性.下面是一些测试代码,显示了我希望如何工作.但是我没有得到预期的行为.

class Basket(object):

  def __init__(self):
    # add all the properties
    for p in self.PropNames():
      setattr(self, p, property(lambda : p) )

  def PropNames(self):
    # The names of all the properties
    return ['Apple', 'Pear']

  # normal property
  Air = property(lambda s : "Air")

if __name__ == "__main__":
  b = Basket()
  print b.Air # outputs: "Air"
  print b.Apple # outputs: <property object at 0x...> 
  print b.Pear # outputs: <property object at 0x...> 
Run Code Online (Sandbox Code Playgroud)

我怎么能让这个工作?

Ste*_*tef 13

您需要在类(即:)上设置属性self.__class__,而不是在对象上设置属性(即:)self.例如:

class Basket(object):

  def __init__(self):
    # add all the properties
    setattr(self.__class__, 'Apple', property(lambda s : 'Apple') )
    setattr(self.__class__, 'Pear', property(lambda s : 'Pear') )

  # normal property
  Air = property(lambda s : "Air")

if __name__ == "__main__":
  b = Basket()
  print b.Air # outputs: "Air"
  print b.Apple # outputs: "Apple"
  print b.Pear # outputs: "Pear"
Run Code Online (Sandbox Code Playgroud)

对于它的价值,你p在循环中创建lamdas的用法并没有给出你期望的行为.由于在p循环中更改了值,因此循环中设置的两个属性都返回相同的值:最后一个值p.