具有多个 parents 的多重继承

Multiple inheritance with multiple parents

基础超class.
它有实例变量= sides.
它有 show() 方法,它给出 sides 的值。

Circle继承Base.
它有 show() 方法打印 classname.

Triangle继承Base.
它有 show() 方法打印 classname.

Square继承Base.
它有 show() 方法打印 classname.

Shape继承Circle,Triangle,Square.
它有 show() 方法打印 "i'm in shape"

我们必须创建 Shape class 的实例并访问 show() 方法 Circle class 使用创建的实例。

我只想访问 Circleshow() 方法,而不是 show()[= Shapeclass.

的 69=] 方法

我该怎么做?

class Base:
    def __init__(self,sides):
        self.sides=sides

    def show(self):
        return self.sides

class Triangle(Base):
    def show(self):
        print("Triangle")

class Square(Base):
    def show(self):
        print("Square")

class Circle(Base):
    def show(self):
        print("Circle")

class Shape(Circle,Square,Triangle):
    def __init__(self):
        super(Shape,self).show()
    def show(self):
        print("i am in shape")

a=Shape()
a.show()

我试图让输出为:

Circle

但是代码给我的输出是:

Circle
i am in shape

如果我必须使用 Shape class 的实例通过 a.show() 调用 Circle class 的 show 方法,代码会发生什么变化?

你应该保持 super(Shape,self).show() 不变,只实例化 Shape,它将打印 Circle,如下所示。您调用的 exta a.show() 正在打印额外的 i am in shape

class Shape(Circle,Square,Triangle):

    def __init__(self):
        super(Shape,self).show()

    def show(self):
        print("i am in shape")

#The constructor is called
a=Shape()
#Circle

#The show function of class Shape is called
a.show()
#i am in shape

如果要显式访问 Circleshow 方法,则需要实例化该对象。

a=Circle(2)
a.show()
#Circle

此外,请查看:How does Python's super() work with multiple inheritance? 了解有关 super 如何实现多重继承的更多信息