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

标签 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)

最佳答案

恭喜,您已经发现了 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/

相关文章:

python - Windows 10 重新安装后 Autopep8 和其他模块无法工作

python - 在遍历 pandas 数据框时更新列中的值

python - 如何检查变量中是否存在除整数之外的任何内容?

c++ - C++ 中的密封类和虚拟继承

c# - 如何强制从抽象类继承的类不使用其基类?

python - Django - 更改选择项目的显示

python - 创建 html 格式的报告

c++ - 我搞砸了我的遗产

php - 通过父方法终止执行

c# - 将派生类转换为 C# 中的另一个派生类