动态属性需要显式调用\uu get\uuuuuu(Python)

2024-03-29 13:17:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在试验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__方法来获取它的值吗?你知道吗


Tags: theselfgetreturnobjectfoovaluedef
1条回答
网友
1楼 · 发布于 2024-03-29 13:17:23

正如jornsharpe所指出的,上面的代码在实例上而不是在类上创建属性。你知道吗

为了解决这个问题,Bar1Bar2可以是相同基类的子类,如下所示:

class Foo(dict):
    def __init__(self):
        self['bar1'] = Bar1()
        self['bar2'] = Bar2()

class BarBase(object):
    @property
    def value(self):
        return self.compute_value()

class Bar1(BarBase):
    def compute_value(self):
        return 'I am bar1.'

class Bar2(BarBase): 
    def compute_value(self):
        return 'I am bar2.'

foo = Foo()
print(foo['bar1'].value)
print(foo['bar2'].value)

相关问题 更多 >