Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance and base class method call python

I would like a method in a base class to call another method in the same class instead of the overriding method in an inherited class. I would like the following code to print out

Class B: 6

Class A: 9

Can this be done?


# Base class definition
class ClassA(object):
    def __init__(self):
        print("Initializing A")

    # hoping that this function is called by this class's printFnX
    def fnX(self, x):
        return x**2

    def printFnX(self, x):
        print("ClassA:",self.fnX(x))

# Inherits from ClassA above
class ClassB(ClassA):
    def __init__(self):
        print("initizlizing B")

    def fnX(self, x):
        return 2*x

    def printFnX(self, x):
        print("ClassB:", self.fnX(x))
        ClassA.printFnX(self,x)

bx = ClassB()
bx.printFnX(3)
like image 900
fodon Avatar asked Oct 20 '11 20:10

fodon


1 Answers

Congratulations, you've discovered the motivating use case for Python's double-underscore name mangling :-)

For the details and a worked-out example see: http://docs.python.org/tutorial/classes.html#private-variables and at http://docs.python.org/reference/expressions.html#atom-identifiers .

Here's how to use it for your example:

# Base class definition
class ClassA(object):
    def __init__(self):
        print("Initializing A")

    # hoping that this function is called by this class's printFnX
    def fnX(self, x):
        return x**2
    __fnX = fnX

    def printFnX(self, x):
        print("ClassA:",self.__fnX(x))

# Inherits from ClassA above
class ClassB(ClassA):
    def __init__(self):
        print("initizlizing B")

    def fnX(self, x):
        return 2*x

    def printFnX(self, x):
        print("ClassB:", self.fnX(x))
        ClassA.printFnX(self,x)

bx = ClassB()
bx.printFnX(3)

The use case is described as a way of implementing the Open-Closed Principle in "The Art of Subclassing" found at http://www.youtube.com/watch?v=yrboy25WKGo&noredirect=1 .

like image 101
Raymond Hettinger Avatar answered Oct 03 '22 21:10

Raymond Hettinger