我希望通过成员函数在类中定义属性。 下面是一些测试代码,显示我希望它如何工作。但是我没有得到预期的行为。
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...>
我怎样才能让它发挥作用?
最佳答案
您需要在类上设置属性(即: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"
就其值(value)而言,您在循环中创建 lamda 时对 p
的使用并没有提供您期望的行为。由于 p
的值在循环过程中发生了变化,因此循环中设置的两个属性都返回相同的值:p
的最后一个值。
关于python - 如何在 __init__ 中定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1454984/