- 所有特殊方法以__开始,__结束,类似__init__ & __del__
- 算术运算符:
- __add__(self, other): 使用加运算符
- __sub__(self, other): 使用减运算符
- __mul__(self, other): 使用乘运算符
- __div__(self, other): 使用除运算符
- 反运算:
- __radd__(self, other), __rsub__(self, other), __rmul__(self, other), __rdiv__(self, other)
- 大小比较:
- __eq__(self, other): 使用==运算符
- __ne__(self, other): 使用!=运算符
- __lt__(self , other): 使用<运算符
- __gt__(self, other): 使用>运算符
- __le__(self, other): 使用<=运算符
- __ge__(self, other): 使用>=运算符
- 字符串操作:
- 字符串可以像数字一样进行__add__, __mul__进行拼接和复制
- __str__(self): 自动转化为字符串
- __repr__(self): 返回一个用来表示对象的字符串,功能和__str__一样,更加官方
- __len__(self): 返回元素个数
- 字符串可以像数字一样进行__add__, __mul__进行拼接和复制
- 实例1:文件函数的重构
from os.path import join
class FileObject:
"""给文件对象进行包装从而确认在删除时文件流关闭"""
def __init__(self, filepath='~', filename='test.txt'):
# 读写模式打开一个文件
self.file = open(join(filepath, filename), 'r+')
def __del__(self):
self.file.close()
del self.file
print("it is ok")
def main():
file_1 = FileObject('G:\\Python-MOOC')
del file_1
main()
- 实例2:字符串函数的重构
class Force:
def __init__(self, x, y):
self.fx, self.fy = x, y
# self.fx, self.fy = round(x,2), round(y,2)
def show(self):
print("Force<%s, %s>"% (self.fx, self.fy))
def add(self, force2):
x = self.fx + force2.fx
y = self.fy + force2.fy
return Force(x, y)
# 巧妙调用
__add__ = add
def __str__(self):
return "F<%s, %s>" % (self.fx, self.fy)
def __mul__(self, n):
x, y = self.fx*n, self.fy*n
return Force(x, y)
def __eq__(self, force2):
return (self.fx == force2.fx and self.fy == force2.fy)
def __round__(self, n=3):
x, y = round(self.fx, n), round(self.fy, n)
return Force(x, y)
f1 = Force(0,1)
f2 = Force(2,3)
f3 = f1+f2
# 试着删除和添加 __str__() 看看差异
print("Fadd =%s " % (f3,))
f3 = f2*4.2
print(round(f3))
print("Fmul=%s" % round(f3))
print("%s == %s? -> %s"% (f1, f2, f1==f2))