python @property setter delegation

时间:2017-06-02 14:52:30

标签: python

我有一个对象,上面有一堆@property个getter和setter。我想委托给那个对象,包括委托获取和设置。我还希望能够覆盖委托类中的某些setter。如上所述的授权here适用于getter,但不适用于setter。有没有一种简单的方法可以做到这一点,而不是冗长地复制所有@property setter?

例如,在下文中,基础@a.setter永远不会被命中:

class A:
  _a = 'A.a'
  _b = 'A.b'

  @property
  def a(self):
    print('A.a.getter')
    return self._a

  @a.setter
  def a(self, a):
    print('A.a.setter')
    self._a = a

  @property
  def b(self):
    print('A.b.getter')
    return self._b

  @b.setter
  def b(self, b):
    print('A.b.setter')
    self._b = b

class B(object):
  _A = None

  def __init__(self, A):
    self._A = A

  @property
  def b(self):
    print('B.b.getter')
    return self._A.b

  @b.setter
  def b(self, b):
    print('B.b.setter')
    self._A.b = b

  def __getattr__(self, name):
    return getattr(self._A, name)

b = B(A())
print(b.a)
b.a = 123
b.b = 456

1 个答案:

答案 0 :(得分:2)

不确定您使用__setattr__的方式,但这对我有用:

class A(object):
  _a = 'A.a'

  @property
  def a(self):
    print('A.a.getter')
    return self._a

  @a.setter
  def a(self, a):
    print('A.a.setter')
    self._a = a

class B(object):
  _A = None

  def __init__(self, A):
    self._A = A
    self.b = 'B.b'

  def __getattr__(self, name):
    return getattr(self._A, name)

  def __setattr__(self, name, value):
    try:
        super(B, self).__setattr__(name, value)
    except AttributeError:
        setattr(self._A, name, value)

b = B(A())
print(b.a)
b.a = 78

输出:

A.a.getter
A.a
A.a.setter

更新:在Python 2中,您必须使用new-style classes