Inheritance and base class method call python

后端 未结 2 1964
长发绾君心
长发绾君心 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()
    bx.printFnX(3)

提交回复
热议问题