Python中使用多重继承

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/WhoisPo/article/details/88564033

在Python中(包括比较成熟的面向对象语言,比如Java, C#)中,一般只能进行单继承,当然C++是多继承的。多继承会使得继承结构比较复杂,不容易理清,这估计就是为什么后来新的面向对象语言中,没有多继承的原因。虽然这些语言不能进行多继承,但可以通过接口来替代,比如让类实现多个接口,效果一样。

说了这么多,再回到Python来,我之前以为Python中也只能实现单一继承,后来才知道可以多重继承。 下面是一个多重继承的例子。
分别有三个类,Point、Size、Rectangle类,Rectangle继承Point和Size,程序很简单,比较好理解。

class Point:
    x = 1.0
    y = 2.0
    z = 3.0

    def __init__(self, x, y):
        self.x = x
        self.y = y
        print("Point Constructor")

    def __str__(self):
        return "{X:" + str(self.x) + ",Y:" + str(self.y) + "}"


class Size:
    width = 0.0
    height = 0.0

    def __init__(self, width, height):
        self.width = width
        self.height = height
        print("Size Constructor")

    def __str__(self):
        return "{Height:" + str(self.height) + ",Width:" + str(self.width) + "}"


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

    def __str__(self):
        return Point.__str__(self) + "," + Size.__str__(self)


x1 = Point(3, 4)
t1 = Size(10, 10)
p1 = Rectangle(3, 4, 10, 10)
print(x1)
print(t1)
print(p1)
print(x1.z)

输出结果

Point Constructor
Size Constructor
Point Constructor
Size Constructor
Rectangle Constructor
{X:3,Y:4}
{Height:10,Width:10}
{X:3,Y:4},{Height:10,Width:10}
3.0

一般如果要在子类中调用父类被覆盖的方法,使用super().method(),这种方法适合单继承。 上面的例子是多继承,有两个子类的__init__()方法,因此需要使用父类的名称,就像上面程序中使用的那样。

Point.__init__(self, x, y)
Size.__init__(self, height, width)

猜你喜欢

转载自blog.csdn.net/WhoisPo/article/details/88564033
今日推荐