(100 days, 2 hours, fourth day) Method rewriting and operator overloading

One, method rewrite

If the function of your parent class method cannot meet your needs, you can override the method of your parent class in the subclass.

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

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

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

  

Two, operator overloading

Operator overloading is to redefine the existing operators and give them another function to adapt to different data types.

When using print to output objects, as long as you define the __str__(self)method yourself , the data returned from this method will be printed

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)

Guess you like

Origin blog.csdn.net/zhangxue1232/article/details/109367408