我有这样一个类:
class Foo(object):
def __init__(self):
self.bar = property(self.get_bar)
def get_bar(self):
return "bar"
print Foo().bar #this prints <property object at 0x0051CB40>
我看过 How do Python properties work? , How to set a python property in __init__ ,但他们都使用装饰器方法,我不这样做,因为我想要一个不同的名称。我需要访问 self
我如何让属性正常运行?
最佳答案
你需要做一个小改动:
class Foo(object):
def get_bar(self):
return "bar"
bar = property(get_bar)
print Foo().bar # prints bar
属性需要是类的属性,而不是实例; descriptor就是这样协议(protocol)有效。
关于Python 属性返回属性对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21812092/