Python中的工厂函数笔记
在Python 2.2之前类和类型是分开的,类就是属性和方法的封装,类型就是整型、字符型、浮点型、字符串,在Python之后作者将两者进行统一,将int()、str()、list()等这些BIF转换成工厂函数。
>>> type(len)
<class 'builtin_function_or_method'>
如果输入type(len)返回内容符合BIF的概念。
>>> type(int)
<class 'type'>
>>> class C:
pass
>>> type(C)
<class 'type'>
因此所谓的工厂函数,可以理解为类对象。
>>> int('123')
123
>>> a = int('123')
>>> b = int('456')
>>> a + b
579
在以前这样的做法是调用int()函数,把参数转换为整型;现在是实例化一个int的对象a,传入的参数为123;在执行a +b 的时候Python实际上是在执行两个对象相加的操作。Python还提供了自定义对象的数值处理,对算术方法进行重载。
>>> 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(3)
>>> b = New_int(5)
>>> a + b
-2
>>> a - b
8
New_int继承于int,然后对在进行a + b 运算时,返回的是int类的__sub__方法。而如果此处不调用int类会出现无限循环的问题。
>>> class Try_int(int):
def __add__(self, other):
return self + other
def __sub__(self, other):
return self - other
>>> a = Try_int(3)
>>> b = Try_int(5)
>>> a + b
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
a + b
File "<pyshell#29>", line 3, in __add__
return self + other
File "<pyshell#29>", line 3, in __add__
return self + other
File "<pyshell#29>", line 3, in __add__
return self + other
[Previous line repeated 991 more times]
RecursionError: maximum recursion depth exceeded
要想正确运行可以在返回前面加上int(),这样返回的是整型的相加
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(3)
>>> b = Try_int(5)
>>> a + b
8