fod*_*don 13 python inheritance
我希望基类中的方法在同一个类中调用另一个方法而不是在继承的类中调用重写方法.我想打印下面的代码
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)
Run Code Online (Sandbox Code Playgroud)
Ray*_*ger 49
恭喜,您已经发现了Python的双下划线名称修改的激励用例:-)
有关详细信息和已完成的示例,请参阅:http://docs.python.org/tutorial/classes.html#private-variables和http://docs.python.org/reference/expressions.html#atom-标识符.
以下是如何将它用于您的示例:
# 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)
Run Code Online (Sandbox Code Playgroud)
用例被描述为在http://www.youtube.com/watch?v=yrboy25WKGo&noredirect=1上找到的"子类化艺术" 中实现开放封闭原则的一种方式.
小智 -5
fnX通过 make和两个类方法可以实现相同的效果printFnX。
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)
Run Code Online (Sandbox Code Playgroud)