Python多重继承问题,新手求解答


class Point(object):
    def __init__(self,x,y):
        self.x = x
        self.y = y

    def string(self):
        print("X:{0},Y:{1}".format(self.x,self.y))

class Circle(Point):
    def __init__(self,x,y,radius):
        super(Circle, self).__init__(x,y)
        self.radius = radius

    def string(self):
        print("该图形初始化点为:X:{0},Y:{1};半径为:{2}".format(self.x,self.y,self.radius))

class Size(object):
    def __init__(self,width,height):
        self.width = width
        self.height = height

    def string(self):
        print("Width:{0},Height:{1}".format(self.width,self.height))

class Rectangle(Point,Size):
    def __init__(self,x,y,width,height):
        super(Rectangle,self).__init__(x,y,width,height)

    def string(self):
        print("该图形初始化点为:X:{0},Y:{1};长宽分别为:Width:{2},Height:{3}".format(self.x,self.y,self.width,self.height))



if __name__ =='__main__':
    c = Circle(5,5,8)
    c.string()
    r1 = Rectangle(15,15,15,15)
    r1.string()
    r2 = Rectangle(40,30,11,14)
    r2.string()

当执行时出现报错
提示:Traceback (most recent call last):
File "D:/py/class/2-6.py", line 39, in
r2 = Rectangle(40,30,11,14)
File "D:/py/class/2-6.py", line 28, in init
super(Rectangle,self).__init__(x,y,width,height)
TypeError: init() takes 3 positional arguments but 5 were given

这个错误的出现,是因为rectangle类的构造方法中调用了父类的构造方法,该类继承了两个类,调用的是左边,也就是point类的构造方法,point类中
构造方法想要得到三个参数,self,x,y,你在rectangle里却传入了5个,self默认传入。

class Rectangle(Point,Size):
    def __init__(self,x,y,width,height):
        Point.__init__(self, x, y)
        Size.__init__(self, width, height)

要这么改。
https://blog.csdn.net/qq_35649686/article/details/104654727
,我也是刚开始学python,上面这个是我整理的一个笔记,你可以参考一下。如果发现错误,请及时告诉我。

刚才试了一下,这么改是可以的。运行结果如下:

该图形初始化点为:X:5,Y:5;半径为:8
该图形初始化点为:X:15,Y:15;长宽分别为:Width:15,Height:15
该图形初始化点为:X:40,Y:30;长宽分别为:Width:11,Height:14
def __init__(self,x,y,width,height):
super(Rectangle,self).__init__(x,y,width,height)
->
def __init__(self,x,y,width,height):
size = Size(width, height)
pt = Point(x,y)
super(Rectangle,self).__init__(pt,size)