医院网站备案,北京网站制作公司报价,雄安专业网站建设公司,济南网站建设v芯企优互联不错1 python运算符重载之构造函数和迭代器
python运算符重载是在类方法中拦截内置操作-当类的实例使用内置操作时#xff0c;pytho自动调用对应方法#xff0c;并且返回操作结果。
NO#描述1拦截运算运算符重载拦截内置操作#xff0c;比如打印、函数调用、点号运算、表达式运…1 python运算符重载之构造函数和迭代器
python运算符重载是在类方法中拦截内置操作-当类的实例使用内置操作时pytho自动调用对应方法并且返回操作结果。
NO#描述1拦截运算运算符重载拦截内置操作比如打印、函数调用、点号运算、表达式运算等2类似内置重载运算符让类实例的行为类似内置操作3特定名称运算符重载通过定义特定名称的类方法类实现4双下划线重载的方法名前后都有双下划线
1.1 常见运算符重载
NO方法内置操作描述1init构造函数cMyClass()2del析构函数对象回收3add运算符如果没有__iadd__xyxy4or运算符|如果没有_ior__x|yx|y5repr,str打印print(x)、repr(x)、str(x)6call函数调用x(*args,**kargs)7getattr点号运算x.attr8setattr属性赋值x.attrvalue9delattr删除属性del x.attr10getattribute属性获取x.attr11getitem索引分片运算x[key]x[m:n]12setitem索引分片赋值x[key]valuex[m:n]序列13delitem索引分片删除del[key]del[m:n]14len长度len(x)15bool布尔测试bool(x)16ltgtlegeeqne关系运算符xyxyxyxyxyx!y17radd右侧加法Otherx18iadd增强加法xy19iternext迭代环境Iiter(X)next(I)for循环20contains成员关系item in x21index整数值hex(x)bin(x)oct(x)o(x)22enterexit环境管理with obj as var:23getset描述符属性x.attr,x.attrvalue,dle x.attr24new创建在__init__之前创建对象
1.2 init
python类调用小括号()创建实例时会自动调用实例的构造函数__init__()。 class A:def __init__(self):print(A.__init__) class B(A):def __init__(self):print(B.__init__) class C(A):pass aA()
A.__init__
# 子类和父类有init自动调用子类initbB()
B.__init__
# 子类无init自动调用父类initcC()
A.__init__1.3 sub
python实例使用减法-表达式会自动调用实例的__sub__()方法。 class MyNumber:def __init__(self,begin):self.databegindef __sub__(self,other):# 拦截减法(-)表达式return MyNumber(self.data-other) n1MyNumber(5)n2n1-3n2.data
21.4 getitem__和__setitem
python实例使用索引和分片获取值时会自动调用实例的__getitem__()方法
设置值时会自动调用__setitem方法
迭代环境会自动调用__getitem__()方法 class MyIndex:def __getitem__(self,index):# []索引获取值时调用getitemreturn index*2miMyIndex()mi[2]
4for i in range(5):print(mi[i],end )
0 2 4 6 8 class MySlice:data[9,7,5,2,6,8]def __getitem__(self,index):# [:]分片获取值时调用getitemprint(索引:,index)return self.data[index] msMySlice()ms[0]
索引: 0
9ms[1]
索引: 1
7ms[-1]
索引: -1
8ms[3:6]
索引: slice(3, 6, None)
[2, 6, 8]ms[1:]
索引: slice(1, None, None)
[7, 5, 2, 6, 8]ms[:-1]
索引: slice(None, -1, None)
[9, 7, 5, 2, 6]ms[::2]
索引: slice(None, None, 2)
[9, 5, 6] class MySetitem:def __init__(self):self.changed{}def __setitem__(self,key,value):# 索引[]设置值时调用setitemself.changed[key]valuedef __getitem__(self,key):return self.changed[key]msMySetitem()ms[s]梯阅线条ms[s]
梯阅线条 class MyStep:def __getitem__(self,i):# for循环迭代时调用getitemprint(i,end )return self.data[i]msMyStep()ms.data梯阅线条ms[0]
0 梯for item in ms:print(item,end )
0 梯 1 阅 2 线 3 条 4 1.5 iter__和__next
python迭代环境先调用__iter__()方法不存在时再调用__getitem__()方法进行索引操作。
iter()方法返回迭代对象迭代对象循环调用__next__()方法直到发生StopIteration异常。
迭代环境循环调用__getitem__()方法直到发生IndexError异常。
迭代器对象具有__next__方法的对象
可迭代对象具有__iter__方法的对象
可迭代对象调用__iter__方法返回迭代器对象再调用__next__方法
1.5.1 单迭代器对象
iter()方法返回实例对象本身为单迭代器对象生成器函数和表达式、map、zip等 class MyIter:def __init__(self,start,stop):self.valuestart-1self.stopstop# 可迭代迭代对象拥有__iter__方法返回迭代器对象 def __iter__(self):return selfdef __next__(self):# 迭代器对象拥有__next__方法if self.valueself.stop:raise StopIterationself.value1return self.value*2 for i in MyIter(1,5):# for迭代环境循环调用迭代器对象的next方法print(i,end )
2 4 6 8 10 miMyIter(1,5)iiter(mi)#等效于mi.__iter__()i
__main__.MyIter object at 0x01269A50
# 等效于 i.__next__()next(i)
2next(i)
4next(i)
6next(i)
8next(i)
10next(i)
Traceback (most recent call last):File pyshell#146, line 1, in modulenext(i)File pyshell#134, line 9, in __next__raise StopIteration
StopIteration [i for i in MyIter(1,5)]
[2, 4, 6, 8, 10][i for i in MyIter(1,5)]
[2, 4, 6, 8, 10]
# mi的__iter__()返回实例本身为单次迭代器
# 类似的有生成器函数和表达式、map、zipmiMyIter(1,5)[i for i in mi]
[2, 4, 6, 8, 10][i for i in mi]
[]miMyIter(1,5)for x in mi:for y in mi:print(xy,end )
6 8 10 12 def mygenerate(start,stop):for i in range(start,stop1):yield i*2 for i in mygenerate(1,5):print(i,end )2 4 6 8 10 1.5.2 多迭代器对象
iter()方法返回新迭代器对象为多迭代器对象比如range、列表等
class MySkipIterator:def __init__(self,wrapped):self.wrappedwrappedself.offset0# 迭代器对象拥有__next__方法def __next__(self):print(__next__)# 证明 __next__ 被调用if self.offsetlen(self.wrapped):print(StopIteration)raise StopIterationelse:itemself.wrapped[self.offset]self.offset2return item
class MySkipObject:def __init__(self,wrapped):self.wrappedwrapped# 可迭代迭代对象拥有__iter__方法# 返回拥有__next__方法的迭代器对象def __iter__(self):# __iter__返回新的迭代器对象为多个迭代器对象# 类似的有range、列表等print(__iter__)# 证明 __iter__ 被调用return MySkipIterator(self.wrapped)if __name__ __main__:s1abcdefmsoMySkipObject(s1)iiter(mso)print(next(i),next(i),next(i))print()#for循环先调用iter生成迭代器再一直调用next方法只到报错for x in mso:print(x,end )print()for x in mso:for y in mso:print(xy,end )C:\Users\Administrator\Desktoppython 新文件 1.py
__iter__
__next__
__next__
__next__
a c e__iter__
__next__
a __next__
c __next__
e __next__
StopIteration__iter__
__next__
__iter__
__next__
aa __next__
ac __next__
ae __next__
StopIteration
__next__
__iter__
__next__
ca __next__
cc __next__
ce __next__
StopIteration
__next__
__iter__
__next__
ea __next__
ec __next__
ee __next__
StopIteration
__next__
StopIteration