Python基础入门学习笔记 042 魔法方法:算术运算

发布时间 2023-08-23 10:59:15作者: 一杯清酒邀明月
python2.2以后,对类和类型进行了统一,做法就是讲int()、float()、str()、list()、tuple()这些BIF转换为工厂函数(类对象):
 1 >>> type(len)
 2 <class 'builtin_function_or_method'>            #普通的BIF
 3 >>> type(int)
 4 <class 'type'>             #工厂函数(类对象),当调用它们的时候,其实就是创建了一个相应的实例对象
 5 >>> type(dir)
 6 <class 'builtin_function_or_method'>
 7 >>> type(list)
 8 <class 'type'>
 9 
10 >>> a = int('123')        #创建一个相应的实例对象a
11 >>> b = int('345')
12 >>> a + b              #python在两个对象进行相加操作
13 468

 举个例子,下面定义一个比较特立独行的类:

 1 >>> class New_int(int):
 2     def __add__(self,other):
 3         return int.__sub__(self,other)
 4     def __sub__(self,other):
 5         return int.__add__(self,other)
 6 
 7     
 8 >>> a = New_int(3)
 9 >>> b = New_int(5)
10 >>> a + b    #两个对象相加,触发 __add__(self,other)方法
11 -2
12 >>> a - b
13 8
14 >>>

实例2:

 1 >>> class New_int(int):
 2     def __add__(self,other):
 3         return (int(self) + int(other))       #将self与other强制转换为整型,所以不会出现两个对象相加触发__add__()方法
 4     def __sub__(self,other):
 5         return (int(self) - int(other))
 6 
 7     
 8 >>> a = New_int(3)
 9 >>> b = New_int(5)
10 >>> a + b
11 8