是否可以进行简单的财产委派?

时间:2019-07-19 08:30:10

标签: python properties

在下面的代码中,所有Test()对象都依赖一个Aux()帮助器。助手具有属性prop。我想要的听起来很简单:通过Test类API导出该属性(仅该属性)。

实际上,将其明确编写非常简单:

class Aux:
    def __init__(self):
        self._prop = 0 

    @property
    def prop(self):
        print("read:", self._prop)
        return self._prop

    @prop.setter
    def prop(self, val):
        print("write:", val)
        self._prop = val 

    # other Aux methods here

class Test: 
    _aux = Aux()

    @property
    def prop(self):
        return self._aux.prop

    @prop.setter
    def prop(self, val):
        self._aux.prop = val 

    # other Test methods here

# try it out:
t = Test()
print(t.prop) # read: 0
t.prop = 123  # write: 123
print(t.prop)

但是我想过一会儿我可以以某种方式使用直接引用。这是错误的:

class Test: 
    prop = Aux.prop     # WRONG! (references `_prop` attr in this class, not in the helper)
    prop = Aux().prop   # WRONG! (equals to simple prop = 0)

但也许:

class Test: 
    prop = property(...)   # BUT HOW?

但是过了一会儿我找不到一个简单的prop=...解决方案。现在我很好奇。是否存在?


有一个类似的问题python @property setter delegation,但对我没有帮助。我不想委派所有事情。

0 个答案:

没有答案
相关问题