分享
  1. 首页
  2. 主题
  3. Python

Python中类的特殊方法详解

maiziedu · · 3430 次点击 · 开始浏览 置顶
这是一个创建于 的主题,其中的信息可能已经有所发展或是发生改变。

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

有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

关注微信
3430 次点击 ∙ 1 赞
暂无回复
添加一条新回复 (您需要 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传

用户登录

没有账号?注册
(追記) (追記ここまで)

今日阅读排行

    加载中
(追記) (追記ここまで)

一周阅读排行

    加载中

关注我

  • 扫码关注领全套学习资料 关注微信公众号
  • 加入 QQ 群:
    • 192706294(已满)
    • 731990104(已满)
    • 798786647(已满)
    • 729884609(已满)
    • 977810755(已满)
    • 815126783(已满)
    • 812540095(已满)
    • 1006366459(已满)
    • 692541889

  • 关注微信公众号
  • 加入微信群:liuxiaoyan-s,备注入群
  • 也欢迎加入知识星球 Go粉丝们(免费)