【发布时间】:2016-05-08 16:52:05
【问题描述】:
我正在试验property,以便在运行时向对象添加属性。我有下面的代码(我知道这有点疯狂,但我认为它会起作用):
class Foo(dict):
def __init__(self):
self['bar1'] = Bar()
self['bar1'].value = property(self.value_bar1)
self['bar1'].other_value = property(Bar.other_value_bar1)
self['bar2'] = Bar()
self['bar2'].value = property(self.value_bar2)
self['bar2'].other_value = property(Bar.other_value_bar2)
@staticmethod
def value_bar1(instance):
return 'I am bar1.'
@staticmethod
def value_bar2(instance):
return 'I am bar2.'
class Bar(object):
def other_value_bar1(self):
return 'I am the other bar1.'
def other_value_bar2(self):
return 'I am the other bar2.'
foo = Foo()
print(foo['bar1'].value.__get__(foo['bar1']))
print(foo['bar2'].value)
print(foo['bar1'].other_value.__get__(foo['bar1']))
print(foo['bar2'].other_value)
它返回:
I am bar1.
<property object at 0x7f3e9338a1d8>
I am the other bar1.
<property object at 0x7f3e9338a228>
有人可以解释为什么我需要显式调用属性的__get__ 方法来获取它的值吗?
【问题讨论】:
-
因为您是在实例上创建属性,而不是在类上。
-
我明白了。在实际代码中,我试图让
Bar的两个实例根据两个不同的公式计算同一属性的值。我可能不得不考虑另一种方式。谢谢。 -
也许它们应该是同一基类的不同子类的实例。
-
当然,这听起来是最好的方法。这也将使代码更易于阅读!
标签: python python-3.x properties