gpt4 book ai didi

python - 继承和基类方法调用python

转载 作者:太空狗 更新时间:2023-10-29 17:21:26 25 4
gpt4 key购买 nike

我希望基类中的方法调用同一个类中的另一个方法,而不是继承类中的覆盖方法。我想打印出下面的代码

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)

最佳答案

恭喜,您已经发现了 Python 双下划线名称重整的激励用例:-)

有关详细信息和已解决的示例,请参阅:http://docs.python.org/tutorial/classes.html#private-variableshttp://docs.python.org/reference/expressions.html#atom-identifiers .

以下是如何在您的示例中使用它:

# 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)

用例被描述为实现 Open-Closed Principle 的一种方式在“子类化的艺术”中找到 http://www.youtube.com/watch?v=yrboy25WKGo&noredirect=1 .

关于python - 继承和基类方法调用python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7841812/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com