An elegant way of overloading Python class properties

Question!

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 = property(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.

By : BasicWolf


Answers

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.

By : rodrigo


This video can help you solving your question :)
By: admin