开发者

An elegant way of overloading Python class properties

Consider a base class:

class A(object):
   def __init__(self, x):
      self._x = x

   def get_x(self):
      #...
      return self._x

   def set_x(self, x):
      #...
      self._x = x

   x = prop开发者_如何学Pythonerty(get_x, set_x)

and a derived class:

class B(A):
   def set_x(self, x):
      #...
      self._x = x**2

   x = property(A.get_x, set_x)

Is there an elegant way of overloading set_x() in class B, without re-declaring it and the property x? Thank you.


Add an extra layer of indirection (i.e. use a hook):

class A(object):
    def __init__(self, x):
        self._x = x

    # Using a _get_hook is not strictly necessary for your problem...
    def _get_hook(self):
        return self._x
    def get_x(self):
        return self._get_hook()

    # By delegating `set_x` behavior to `_set_hook`, you make it possible
    # to override `_set_hook` behavior in subclass B.
    def _set_hook(self, x):
        self._x=x
    def set_x(self, x):
        self._set_hook(x)

    x = property(get_x, set_x)

class B(A):
    def _set_hook(self, x):
        print('got here!')
        self._x = x**2

b=B(5)
b.x=10
# got here!
print(b.x)
# 100

For modern versions of Python, you can also use the @property decorator:

class A(object):

   @property
   def x(self):
      return self._get_hook()

   @x.setter
   def x(self, x):
      self._set_hook(x)


Try this one:

 class A(object):
    def __init__(self):
        self._x = 0

    def get_x(self):
        #...
        return self._x

    def set_x(self, x):
        #...
        self._x = x

    x = property(get_x, lambda self,x : self.set_x(x))

class B(A):
    def set_x(self, x):
        #...
        self._x = x**2

The extra indirection given by the lambda will make the set_x function virtually.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜