(100天2小时第四天)方法重写和运算符重载

一、方法重写

如果你的父类方法的功能不能满足你的需求,你可以在子类重写你父类的方法。

class Parent:        # 定义父类
    def myMethod(self):
        print('调用父类方法')

class Child(Parent): # 定义子类
    def myMethod(self):
        print('调用子类方法')

c = Child()          # 子类实例
c.myMethod()         # 子类调用重写方法

  

二、运算符重载

运算符重载,就是对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型。

当使用print输出对象的时候,只要自己定义了__str__(self)方法,那么就会打印从在这个方法中return的数据

class Vector:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __str__(self):
        return 'Vector (%d, %d)' % (self.a, self.b)

    def __add__(self, other):
        return Vector(self.a + other.a, self.b + other.b)


v1 = Vector(2, 10)
v2 = Vector(5, -2)
print(v1 + v2)

猜你喜欢

转载自blog.csdn.net/zhangxue1232/article/details/109367408