自Python2.2以后,对类和类型进行了同一,做法就是将int(),float(),str(),list()tuple()这些BIF转换为工厂函数
工厂函数
>>> type(len)
<class 'builtin_function_or_method'>
#len方法用于返回参数的长度
他返回了一句<class 'builtin_function_or_method'>这是个普通的BIF返回的,看一下Int的返回格式
>>> type(int)
<class 'type'>
>>> type(str)
<class 'type'>
>>>
你会发现,它和class(类,撞了衫)如下
>>> class A:
... pass
...
>>> type(A)
<class 'type'>
>>>
所谓的工厂函数,其实就是个class(类),调用时,其实就是实例化一个对象,如下
>>> a = int("123")
>>> b = int("456")
>>> a + b
579
>>>
算数操作符
列举一些常用的算数运算的魔法方法
魔法方法 | 含义 |
---|---|
__add__(self,other) | 定义加法的行为:+ |
__sub__(self,other) | 定义减法行为:- |
__mul__(self,other) | 定义乘法行为;* |
__truediv__(self.other) | 定义除法行为:// |
__mod__(self,other) | 定义取模算法行为;% |
---|---|
__divmod__(self,other) | 定义当做调用__divmod__时的行为 |
__pow__(self,other[,,odulo]) | 定义被当做__pow_-调用或**运算时行为 |
__lshift__(self,other) | 定义按位左移的行为;<< |
__rshift__(self,other) | 定义按位右移的行为;>> |
__and__(self,other) | 定义与操作的行为;‘&’ |
---|---|
__xor__(self,other) | 定义按位异或的行为‘^’ |
__or__(self,other) | 定义按位或的行为‘|’ |
举个例子
class New_int(int):
def __add__(self,other):
return int.__sub__(self,other)
def __sub__(self,other):
return int.__add__(self,other)
源码
运行后
>>> a = New_int(4)
>>> b = New_int(5)
>>> a + b
-1
>>> a - b
9
如果自己写代码,不想调用Python的默认方案行吗?
肯定行啊,但是我们可能会疏忽
看下列代码
class Try_int(int):
def __add__(self,other):
return selt + other
def __sub__(self,other):
return self - other
大家不妨找找错
运行后
>>> a = Try_int(4)
>>> b = Try_int(6)
>>> a +b
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
a +b
File "C:/Users/Administrator/Desktop/__add甲方.py", line 3, in __add__
return selt + other
NameError: name 'selt' is not defined
程序出现了无限递归的情况,为什么
return selt + other
因为这串代码,当对象涉及到,加法时会调用__add__然后,又加法又调用,形成无限的递归。
怎么改
class Try_int(int):
def __add__(self,other):
return int(self) + int(other)
def __sub__(self,other):
return int(self) - int(other)
运行后
>>> a = Try_int(4)
>>> b = Try_int(6)
>>> a + b
10