【问题标题】:Dynamic property needs to call __get__ explicitly (Python)动态属性需要显式调用 __get__ (Python)
【发布时间】: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


【解决方案1】:

正如 jonrsharpe 所说,上面的代码在实例上创建属性,而不是在类上。

为了解决这个问题,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)

【讨论】:

    猜你喜欢
    • 2015-10-20
    • 1970-01-01
    • 2021-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多