Inheritance and base class method call python

后端 未结 2 1965
长发绾君心
长发绾君心 2021-01-31 11:59

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 o

相关标签:
2条回答
  • 2021-01-31 12:29

    The same can be achieved by making fnX and printFnX both classmethods.

    class ClassA(object):
    
        def __init__(self):
            print("Initializing A")
    
        # hoping that this function is called by this class's printFnX
        @classmethod
        def fnX(self, x):
            return x ** 2
    
        @classmethod
        def printFnX(self, x):
            print("ClassA:",self.fnX(x))
    
    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(x)
    
    
    bx = ClassB()<br>
    bx.printFnX(3)
    
    0 讨论(0)
  • 2021-01-31 12:35

    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 .

    0 讨论(0)
提交回复
热议问题