算数运算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)