继承和基类方法调用python [英] Inheritance and base class method call python
本文介绍了继承和基类方法调用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
B类:6
A类: 9
可以这样做吗?
# 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)
推荐答案
同样可以通过 fnX
和 printFnX
两个classmethods。
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)
这篇关于继承和基类方法调用python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文