如何在derivedclass的subclass中使用baseclass的方法?

How to use the method of base class in the subclass of derived class?

我需要 python 才能在下面的程序中使用基础 class 的方法。 我阅读了很多文档,即使在那之后,我也无法弄清楚发生以下情况时 super 是如何工作的。

class Car:
    time = 2
    def __init__(self, color, company,powertrain,velocity):
        self.color = color
        self.company = company
        self.powertrain = powertrain
        self.velocity = velocity

    def speed(self):
        return self.velocity

    def __self__(self):
        return self.powertrain   #just self.powertrain to print it

class Conventional(Car):

    def speed(self):

        return self.velocity *self.time*2

class Electric(Car):

    def __init__(self):
        super().__init__()

    def speed(self):
        return super().velocity * super().time*3

 class Hybrid(Electric,Conventional):

    pass

现在我需要混合对象来使用Car的方法class,我想我可以在这里使用组合概念。但我需要知道 super 在这里是如何工作的。我也知道 mro 获取 python 查找方法的顺序。先生

car = Hybrid("blue", "Audi", "hyrid", 50)
car.speed()

以上代码如果有更好的写法欢迎交流。 我想如果我使用 super() 得到上述问题的解决方案,我就能正确理解 super 的完整功能。 为了查看所有可能性,我使用了不同的语法。不介意

提前致谢

这应该有效:

super(Electric, Electric).speed(self, velocity)

说明: super 可以接受两个可选参数,它应该使用的 superclass(直接 superclass),以及它应该通过 MRO 从以下位置开始搜索的 class: MRO:混合动力 -> 电动 -> 汽车 -> 传统 -> 汽车 通过 Electric,我们可以进行 MRO: 汽车 -> 传统 -> 汽车 (多重继承很糟糕) 当我们这样解析继承时,我们还需要显式传递当前对象(self)。 顺便说一句,你应该修复你的 init,它们不会很好地解析,你应该始终传递 *args,并让 super 为你解析参数。

class Car:
    time = 2
    def __init__(self, color, company,powertrain,velocity):
        self.color = color
        self.company = company
        self.powertrain = powertrain
        self.velocity = velocity

    def speed(self, velocity):
        return self.velocity

    def __self__(self):
        return self.powertrain   #just self.powertrain to print it

class Conventional(Car):
    def __init__(self,*args):
        super().__init__(*args)


    def speed(self):

        return self.velocity *self.time*2

class Electric(Car):

    def __init__(self,*args):
        super().__init__(*args)

    def speed(self):
        return super().velocity * super().time*3

class Hybrid(Electric,Conventional):
    def __init__(self,*args):
        super().__init__(*args)

    def speed(self):
        return super(Electric, Electric
                ).speed(self,50)

car = Hybrid("blue", "Audi", "hyrid", 50)
car.speed()

首先尝试重新组织您的代码。如果您在 Car class speed 方法中使用 self.velocity,则不需要采用第二个参数 velocity 因为您不在方法中使用它,您使用的是在 [=22] 中创建的 self.velocity =]初始化.

并且您可以使用 lambda 函数来 "map" 旧的速度方法来变量

尝试在 Hybrid 中创建 lambda 函数 class

self.speed_carclass = lambda speed x=Car: Car.speed(x)

然后在外面class调用它

hybrid_speed = <class istance>.speed_carclass()

hybrid_speed 将与您创建 Car

时的速度变量的值相同