Python中的工厂函数笔记

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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值