首页 > 代码库 > Python中类的特殊方法详解

Python中类的特殊方法详解

本文和大家分享的主要是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])

  程序的运行结果为:

技术分享

  构造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)

  程序的运行结果为:

技术分享

  构造可比较类

  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)

  程序的运行结果为:

技术分享

  构造可运算类

  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()

  程序的运行结果为:

技术分享

 

 

原文链接:http://www.maiziedu.com/wiki/python/special/

Python中类的特殊方法详解