购物网站设计模版网页设计心得500字
一、运算符重载
1、Python类内置方法
Python常用内置方法,如下:
__init__: 构造函数,在生成对象时调用__del__: 析构函数,释放对象时使用__repr__: 打印,转换__setitem__: 按照索引赋值__getitem__: 按照索引获取值__len__: 获得长度__cmp__: 比较运算__call__: 函数调用__add__: 加运算__sub__: 减运算__mul__: 乘运算__truediv__: 除运算__mod__: 求余运算__pow__: 乘方__str__:返回对象的描述信息,如果不使用__str__方法,直接print,或者return,返回的是对象的内存地址
2、运算符重载
Python同样支持运算符重载,可以对类的内置方法进行重载,例如:
class MyVector:def __init__(self, a, b):self.a = aself.b = bdef __str__(self):return 'Vector (%d, %d)' % (self.a, self.b)def __add__(self,other):return MyVector(self.a + other.a, self.b + other.b)v1 = MyVector(2, 10)
v2 = MyVector(5, -2)
print(v1 + v2)  # 输出结果:Vector (7, 8)
