Base是超类。 它有实例变量=边。 它有show()方法,它给出了双方的价值。
Circle继承Base。 它有show()方法,它打印classname。
三角继承Base。 它有show()方法,它打印classname。
Square继承Base。 它有show()方法,它打印classname。
形状继承圆形,三角形,正方形。 它有show()方法打印“我在形状”
我们必须创建Shape类的实例,并使用创建的实例访问Circle类的show()方法。
我想只访问Circle的show()方法而不是Shape类的show()方法。
我怎么做?
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类的实例通过a.show()调用Circle类的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
如果要显式访问show
的Circle
方法,则需要实例化该对象。
a=Circle(2)
a.show()
#Circle
另外,请查看:How does Python's super() work with multiple inheritance?,了解有关超级如何用于多重继承的更多信息