python 归纳 (四)_运算符重载

# -*- coding: UTF-8 -*-
"""
测试运算符重载 加法

总结:
   python 运算符表达式其实都是调用 类中方法 __xxx__
    +  <--->   __add__  (由python 编译器 自己设置好了映射关系)
   后续假如想自定义运算符   <符号>  <--->  __<自定义>__ 不知道如何玩

"""
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)

if __name__ == '__main__':
    pa = Point(1,2)
    pb = Point(3,4)
    pc = pa + pb     # + 重载
    pc.info()  #Out    (4, 6)

  

猜你喜欢

转载自www.cnblogs.com/sunzebo/p/9563735.html