具有相同方法的Python多重继承

问题描述 投票:0回答:1

我有一个 Time 类和一个 Date 类作为父类,它们都有 get() 方法,即 Time 类获取 h/m/s ,Date 类获取 y/m/d 。 我有 Invoice 类作为从 Date 和 Time 类继承的子类,我希望 Invoice 类的每个对象在创建时都获得 h/m/s 和 y/m/d 属性。 与 show() 方法或 set() 方法等相同

我试过了:

class Time:
    def get(self):
        #geting the h/m/s

class Date:
    def get(self):
        #geting the y/m/s

class Invoice(Time, Date):
    def __init__(self):
        self.get()

但它只能从 Time 类中获取

python class oop multiple-inheritance
1个回答
0
投票

在Python中,当您具有多重继承并且子类调用多个父类中存在的方法时,Python将调用继承声明中列出的第一个父类的方法。在您的情况下,当您调用 self.get() 时,Python 将调用 Time.get(self) 因为在声明类 Invoice(Time, Date) 中 Time 列在 Date 之前。

要从两个父类调用 get 方法,您需要使用类名显式调用它们并将 self 作为参数传递。具体方法如下:

class Time:
    def get(self):
        # getting the h/m/s
        print("Getting time")

class Date:
    def get(self):
        # getting the y/m/d
        print("Getting date")

class Invoice(Time, Date):
    def __init__(self):
        Time.get(self)
        Date.get(self)

在此示例中,当您创建 Invoice 实例时,它将调用 Time 和 Date 的 get 方法。

© www.soinside.com 2019 - 2024. All rights reserved.