小甲鱼零基础python 魔法方法之 算数运算1(P43)

算数运算1

【Python教程】《零基础入门学习Python》_哔哩哔哩_bilibili

1. 概念:

类 - 属性和方法的封装

类型:整型,字符串,浮点型。。。

python 2.2 后作者对两者进行统一,将类型这些BIF函数变为工厂函数(实际是类对象,type(list)--> class type)

				>>> type(list)
				<class 'type'>
				>>> class C:
					pass
				
				>>> type(C)
				<class 'type'>

2. 实际上对象是可以相加的(a, b 就是int的实例化对象)

>>> a = int('123')
>>> b = int('234')
>>> a + b
357

3.通过自定义下面的魔法方法可以自定义计算行为

 

			§ 举例__add__ 和 __sub__方法,自己定义的时候注意无限递归的情形
				1) >>> 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(6)
				>>> a + b
				-3
				>>> a - b
				9
				
			2) 如果改成下面的形式
				>>> class New_int(int):
					def __add__(self, other):
						return self + other 
					def __sub__(self, other):
						return self + other
				
					
				>>> a = New_int(3)
				>>> b = New_int(6)
				>>> a + b      #当a调用add的时候返回的self就是a实例, other是b实例,所以self + other 还是a+b 这样又会去调用add方法导致无限递归
				Traceback (most recent call last):
				  File "<pyshell#23>", line 1, in <module>
				    a + b
				  File "<pyshell#20>", line 3, in __add__
				    return self + other
				  File "<pyshell#20>", line 3, in __add__
				    return self + other
				  File "<pyshell#20>", line 3, in __add__
				    return self + other
				  [Previous line repeated 1022 more times]
				RecursionError: maximum recursion depth exceeded
				
				>>> class New_int(int):
					def __add__(self, other):
						return int(self) + int(other) 
					def __sub__(self, other):
						return int(self) + int(other)
				#加上int把对象变成数值就不会了

Divmod() -- 得到a//b的余数,eg 5//3 --> 2

>>> divmod(5, 3)

(1, 2)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值