Question

I'm basically stuck into a double question of object properties inheritance and extending base class method.

I'm refactoring my code to follow the DRY precept and discuss about the best design solution.

Is there a short and elegant way to make and object inherit properties from a Base Class and extend its existing method

without mapping every properties of object A in object B *without a mess of decorators and properties?*

It seems not to be allowed accessing the properties of the Base Class Object

Example:

class A():
    def __init__(self):
        self.x = "whatever"
        self.y= "cumbersome"
        self.z = "idea"
    def method1(self):
        self.x = self.x.lower()

class B(A):
    def __init__(self):
        self.a = 87
    @method1 
    def method1extended(self):
        self.y =self.y.upper()
  • First problem:

b = B() b.y is not set so we should use a setter and a getter decorator I suppose

  • Second problem

method1 can't be extended easily and doesn't let you access to self.x nor to self.y transformed by method1extended always pointed out the initial self.y value

Even if you try by super() you need to rewrite the entire function

Is there an elegant solution for this?

Was it helpful?

Solution

Try it with the following code.

class A(object):
    def __init__(self):
        self.x = "whatever"
        self.y= "cumbersome"
        self.z = "idea"

    def method1(self):
        self.x = self.x.lower()

class B(A):
    def __init__(self):
         super(B, self).__init__()
         self.a = 87

    def method1(self):
         super(B, self).method1()
         self.y =self.y.upper()

And a list of things we changed:

  • We added that A subclasses from object to get a new-style class. (note this is only reqiured for python version 2)
  • We added the call to object.__init__ in A.__init__. Python does not call these implicitly for you, you have to do it yourself.
  • B.__init__ now calls A.__init__. This again need to be done by you.
  • B.method1extended renamed to B.method1 so that it shadows A.method1.
  • B.method1 calls A.method1 before applying its own changes.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top