一、算术运算
Python2.2以后,对类和类型进行了统一,做法就是将 int()、float()、str()、list()、tuple()这些BIF转换为工厂函数。
所谓的工厂函数,其实就是一个类对象。当你调用他们的时候,事实上就是创建一个相应的实例对象。
发现对象也可以运算,因为Python中无处不对象,当在求a+b等于多少时,事实上Python就是在将两个对象进行相加操作
二、算术操作符
魔方方法 | 含义 |
---|---|
__add__(self,other) | 定义加法的行为:+ |
__sub__(self, other) | 定义减法的行为:- |
__mul__(self, other) | 定义乘法的行为:* |
__truediv__(self, other) | 定义真除法的行为:/ |
__floordiv__(self, other) | 定义整数除法的行为:// |
__mod__(self, other) | 定义取模算法的行为:% |
__divmod__(self, other) | 定义当被divmod()调用时的行为:+ |
__pow__(self, power, modulo=None) | 定义当被power()调用或**运算时的行为:+ |
__lshift__(self, other) | 定义按位左移位的行为:<< |
__rshift__(self, other) | 定义按位右移位的行为:>> |
__and__(self, other) | 定义按位与操作的行为:& |
__xor__(self, other) | 定义异或操作的行为:^ |
__or__(self, other) | 定义按位或操作的行为:| |
# 继承本就存在的类int
class New_int(int):
def __add__(self,other):
# 重定义方法__add__()直接跳转到int.__sub__()
return int.__sub__(self,other)
def __sub__(self,other):
return int.__add__(self,other)