本文和大家分享的主要是python语言中类的特殊方法相关用法,希望对大家有帮助。
构造序列
1._len_(self)
2._getitem_(self,key)
3._setitem_(self,key,value)
4._delitem_(self,key)
程序演示:
myseq.py
class MySeq:
def __init__(self):
self.lseq = ["I","II","III","IV"]
def __len__(self):
return len(self.lseq)
def __getitem__(self,key):
if 0 <= key < 4:
return self.lseq[key]
if __name__ == '__main__':
m = MySeq()
for i in range(4):
print(m[i])
程序的运行结果为:
![1.png](http://studygolang.qiniudn.com/161129/4786c00a1cb5a8ac6d02025071593a97.png)
构造iter
1._iter_(self)
2._next_(self)
程序演示如下:
class MyIter:
def __init__(self,start,end):
self.count = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.count < self.end:
r = self.count
self.count += 1
return r
else:
raise StopIteration
if __name__ == '__main__':
for i in MyIter(1,10):
print(i)
程序的运行结果为:
![2.png](http://studygolang.qiniudn.com/161129/eb82996defd9b668e8e46f68cc4ee86a.png)
构造可比较类
1._it_()
2._le_()
3._gt_()
4._ge_()
5._eq_()
6._ne_()
程序演示如下:
mycmp.py
class MyIter:
def __init__(self,start,end):
self.count = start
self.end = end
def __iter__(self):
return self
def __next__(self):
if self.count < self.end:
r = self.count
self.count += 1
return r
else:
raise StopIteration
if __name__ == '__main__':
for i in MyIter(1,10):
print(i)
程序的运行结果为:
![3.png](http://studygolang.qiniudn.com/161129/dfe4a9b74acc861bcb78575d66ac2aad.png)
构造可运算类
1._add_()
2._sub_()
3._mul_()
4._div_()
程序演示如下:
class Point:
def __init__(self,x,y):
self.x = x
self.y = y
def __add__(self,oth):
return Point(self.x + oth.x , self.y + oth.y)
def info(self):
print(self.x,self.y)
if __name__ == '__main__':
pa = Point(1,2)
pb = Point(3,4)
pc = pa + pb
pc.info()
程序的运行结果为:
![4.png](http://studygolang.qiniudn.com/161129/0495e3f4c6f49ca6596f1cede5bcdfcd.png)
原文链接:http://www.maiziedu.com/wiki/python/special/
有疑问加站长微信联系(非本文作者)