4、python面向对象之多态

来源:互联网 发布:网络话费卡怎么用 编辑:程序博客网 时间:2024/06/05 20:44
# 父类class Animal:    def run(self):        print('Animal is running...')# 子类class Cat(Animal):    def run(self):        print('Cat is running...')# 定义一个方法def run(animal):    animal.run()# 测试run(Animal()) # Animal is running...run(Cat()) # Cat is running...


class Point:    def __init__(self, x, y):        self.x = x        self.y = y    # 对象的数学运算 加法    def __add__(self, other):        return Point(self.x + other.x, self.y + other.y);    def info(self):        print(self.x, self.y)class D3Point(Point):    def __init__(self, x, y, z):        super().__init__(x, y)        self.z = z    def __add__(self, other):        return D3Point(self.x + other.x, self.y + other.y, self.z + other.z);    def info(self):        print(self.x, self.y, self.z)def addObj(a, b):    return a + b# 测试if __name__ == '__main__':    addObj(Point(3,5), Point(7,9)).info() # 10 14    addObj(D3Point(1, 5, 9), D3Point(3, 3, 7)).info() # 4 8 16