zoukankan      html  css  js  c++  java
  • 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/

  • 相关阅读:
    django调试思路
    在python中使用Mongodb
    python中Redis的简要介绍以及Redis的安装,配置
    python3.7中SQLAlchemy安装失败,报错Command errored out with exit status 1
    使用jinjia2时报错 (admin.E403) A ‘django.template.backends.django.DjangoTemplates’ instance must be configured in TEMPLATES in order to use the admin application.
    使用豆瓣API时报错invalid keyid
    Http常用状态码
    python开发工具ipython
    解析GenericOptionsParser
    Sql注入
  • 原文地址:https://www.cnblogs.com/haitaoli/p/10782650.html
Copyright © 2011-2022 走看看