【问题标题】:Python: how to resolve this class inheritancePython:如何解决此类继承
【发布时间】:2013-12-31 15:06:56
【问题描述】:

我有以下课程:

class A:
    def __init__(self,x):
        self.x = x
        self.xp = self.preprocess(x)

    def preprocess(self,x):
        return(x**2)

class B(A):
    def __init__(self,x,y):
       A.__init__(self,x)
       self.y = y

    def results():
       return(self.xp + self.y)

在这个玩具示例中,A 用于读取一些数据 (x) 并对其进行预处理 (xp)。

B 进一步读取一些数据 (y) 并使用来自A 的预处理数据生成结果。

现在我需要创建一个类CCB 的区别完全一样,所以我很想 简单定义为:

class C(B):
    pass

但是,我需要重写A.preprocess() 方法,以便在构造C 时使用正确的预处理。有没有简单直接的方法来做到这一点?

【问题讨论】:

标签: python inheritance overriding


【解决方案1】:

是的,只需在C 上定义一个新的preprocess 方法:

class C(B):
    def preprocess(self, x):
        return x + x

当使用type(self) is C 调用时,A.__init__() 方法将找到 那个 方法而不是 A 中定义的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多