python - 避免在Python中的父类中使用子方法

标签 python inheritance overriding

假设我有两个 Python 类,如下所示:

class Parent(object):
    def __init__(self):
        self.num = 0

    def fun1(self):
        print 'p.fun1'

    def fun2(self):
        self.fun1()
        print 'p.fun2'

from parent import Parent

class Child(Parent):
    def __init__(self):
        super(Child,self).__init__()

    def fun1(self):
        print 'c.fun1'

    def fun2(self):
        super(Child, self).fun2()
        print 'c.fun2'

如果我调用 Child 的 fun2

from child import Child

test = Child()
test.fun2()

我得到输出:

c.fun1
p.fun2
c.fun2

这意味着对Child.fun2()的调用会导致Parent.fun2()。但在 Parent.fun2() 中,我使用 self.fun1() ,在本例中,它在我的代码中解释为 Child.fun1()测试。

但我真的希望类 Parent 是独立的,并且 Parent.fun2() 的调用始终使用 Parent.fun1()在里面。

如何避免这种情况?

我只知道我可以将 Parent.fun1() 私有(private)化为 Parent.__fun1()。但我还有一些 Parent 实例,我需要在此类之外使用 Parent.fun1() 。这意味着我确实需要重写 fun1()

最佳答案

这就是继承应该如何工作的。对于您需要的行为,您可能需要重新考虑 ParentChild 类的关系,或者更改方法名称或至少创建 Parent 方法classmethodsstaticmethods

这应该可以满足您的需求,但我不太喜欢它。

class Parent(object):
    def __init__(self):
        self.num=0
    def fun1(self):
        print 'p.fun1'
    def fun2(self):
        Parent.fun1(self)
        print 'p.fun2'

Child 类可以保持不变。

在继承链中访问的所有类中,self将始终指向实际实例化的类的实例,而不是在super调用中访问的当前类(或按顺序)找到相关的方法/属性)。所以 self.fun2 将始终指向 Child 类的方法。

关于python - 避免在Python中的父类中使用子方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43273236/

相关文章:

python - 读取 csv 文件时删除空白行

inheritance - “特征A <:B”是什么意思?

c# - 通用抽象类继承

Python使用super覆盖属性,传递参数时出现意外的参数错误

java - 类不是抽象的,不会覆盖父类(super class)中的抽象方法

python - 从 2D lat/lon 矩阵转换为 1D lat/lon 数组

python - 如何计算 Pandas 列中逗号分隔的重复值?

python - 使用python的二进制文件超时

java - 方法引用是否摆脱了可重写的方法调用?

java - 创建自定义覆盖方法问题