• Python中类的特殊方法详解


    原文来自: https://www.cnblogs.com/space007/p/6114759.html

      构造序列

      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/

  • 相关阅读:
    20170225-ALV tree 显示
    20170225-第一件事:SAP模块清单
    20170225 ABAP获取字符串长度/字节长度
    记录001:AS11 BAPI
    Ghost wenjian目录
    20170223-问题001,增强中的E消息 显示为 S模式消息,
    孩子教育分析
    笔记:智能分类
    从市电接信号串联电阻聊到电阻的耐压
    锂聚合物电池和液态锂电池
  • 原文地址:https://www.cnblogs.com/haitaoli/p/10782650.html
Copyright © 2020-2023  润新知