我正在试验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__
方法来获取它的值吗?你知道吗
正如jornsharpe所指出的,上面的代码在实例上而不是在类上创建属性。你知道吗
为了解决这个问题,
Bar1
和Bar2
可以是相同基类的子类,如下所示:相关问题 更多 >
编程相关推荐