动态属性需要显式调用__get__(Python)

时间:2016-05-08 16:52:05

标签: python python-3.x properties

我正在试验 private Rule getRuleFromResult(Fact result){ Rule output=null; Rule current==null; for (int i = 0; i < rules.size(); i++) { current=rules.get(i); if(current.getRuleSize()==1){return current;} if(current.getResultFact().getFactName().equals(result.getFactName())) output=rules.get(i); } return output; } ,以便在运行时向对象添加属性。我有下面的代码(我知道它有点疯狂,但我认为它会起作用):

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> 方法来获取它的值吗?

1 个答案:

答案 0 :(得分:0)

正如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)