A Guide to Python's Magic Methods
Book Source:[https://rszalski.github.io/magicmethods/]
magic methods: 名称前后有双下划线的方法
构造函数和初始化
初始化类实例时,__new__ 方法比__init__方法首先被调用
__del__:当被作为垃圾回收时调用的方法,可以用来做一些额外的清理工作。最好不要使用它来清理占用的资源(端口,文件流,链接),保持良好的代码习惯
自定义类操作函数的使用
两个对象的比较通常是比较这两个对象的引用
__eq__: 可用于 == 比较
__ne__:可用于 != 比较
__lt__:可用于 < 比较
__gt__:可用于 > 比较
__le__:可用于 《= 比较
__ge__:可用于 >= 比较
__cmp__: self < other 返回负数, self == other 返回0,self > other 返回正数,可用于以上所有比较
优先使用__gt__(), __lt__(), __eq__(),如果找不到则使用__cmp__()
string 类型默认是按照字母表前后顺序比较大小的
也可用装饰器@total_ordering 2.7+/3.4+
数字类型的magic method:
一元运算操作符和方法:
__pos___: +some_object
__neg__: -some_object
_abs__: abs(some_object)
__invert__:~some_object(取反操作符)
__round__:round(some_object)
__floor__:math.floor(向下取整)
__ceil__:math.ceil(向上取整)
__trunc__:math.trunc(Truncates x to the nearest Integral toward 0.)
正规算术运算符(some_object + other)
__add__:加法
__sub__:减法
__mul__:乘法
__floordiv__:整数除法
__div__:除法
__truediv__:true division
__mod__:取余%
__divmod__:长除法
__pow__:平方 **
__lshift__:<<
__rshift__:>>
__and__:&
__or__:|
__xor__: ^
反向运算符:(other + some_object)
__radd__/ __rsub__ / __rmul__ /__rfloordiv__ /__rdiv__ /__rtruediv__ /__rmod__ /__rdivmod__ /__rpow__ /__rlshift__ /__rrshift__ /__rand__ /__ror__ /__rxor__
Augmented assignment ( a += b => a = a+b => __iadd__ means += )
__iadd__/ __isub__ / __imul__ /__ifloordiv__ /__idiv__ /__itruediv__ /__imod__ /__idivmod__ /__ipow__ /__ilshift__ /__irshift__ /__iand__ /__ior__ /__ixor__
Type conversion magic methods
___int__ /__long__ /__float__ /__complex__ /__oct__ /__hex__ /__index__ /__trunc__ /__coerce__
Representing your Classes
__str__:str()
__repr__:repr()
__unicode__:unicode()
__format__:格式化
__hash__:hash()
__nonzero__:bool()
__dir__:dir()
__sizeof__:sys.getsizeof()
Controlling Attribute Access
__len__: return length
__getitem__: self[key]
__setitem__:self[key]=value
__delitem__:del self[key]
__iter__:return iterator => for item in object:
__reversed__:reversed() [class should be ordered]
__contains__: 用于 in 和 not in 操作
__missing__:self[key] key不存在时被调用 self.__missing__(key)
Reflection
__instancecheck__:isinstance(instance,class)
__subclasscheck__:issubclass(subclass,class)
Callable Objects
__call__: 可以让类实例当做方法来用 objectA = Class() => objectA(args)
Context Managers
主要用于 with 关键字
__enter__(self): with 块 开始要做的事情,并将返回值赋值给目标 或者 as 后面的变量
__exit__(self,exception_type,exception_value,traceback):with 块结束时要做的事情,正常情况下要返回 True
Abstracet Base Classes
See http://docs.python.org/2/library/abc.html 
Building Descriptor Objects
reference : http://python.jobbole.com/83562/
__set__ /__get__ /__delete__
Copying
__copy__: copy.copy()
__deepcopy__:copy.deepcopy()
Pickling Your Objects
这是有关数据存储序列化的东西
__getinitargs__
__getnewargs__
__getstate__
__setstate__
__reduce__
__reduce_ex__
A Guide to Python's Magic Methods的更多相关文章
- Python 的 Magic Methods 指南(转)
介绍 本指南是数月博客的总结.主题是魔术方法. 什么是魔术方法呢?它们是面向对象Python语言中的一切.它们是你可以自定义并添加“魔法”到类中的特殊方法.它们被双下划线环绕(比如__init__或_ ...
- python的magic methods
https://pycoders-weekly-chinese.readthedocs.io/en/latest/issue6/a-guide-to-pythons-magic-methods.htm ...
- Introspection in Python How to spy on your Python objects Guide to Python introspection
Guide to Python introspection https://www.ibm.com/developerworks/library/l-pyint/ Guide to Python in ...
- Pthon魔术方法(Magic Methods)-描述器
Pthon魔术方法(Magic Methods)-描述器 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.描述器概述 1>.描述器定义 Python中,一个类实现了&quo ...
- Pthon魔术方法(Magic Methods)-反射
Pthon魔术方法(Magic Methods)-反射 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.反射概述 运行时,区别于编译时,指的时程序被加载到内存中执行的时候. 反射 ...
- Pthon魔术方法(Magic Methods)-上下文管理
Pthon魔术方法(Magic Methods)-上下文管理 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.上下文管理方法 __enter__: 进入与此对象相关的上下文.如果 ...
- Pthon魔术方法(Magic Methods)-可调用对象
Pthon魔术方法(Magic Methods)-可调用对象 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.可调用对象方法 __call__: 类中定义一个该方法,实例就可以像 ...
- Pthon魔术方法(Magic Methods)-容器相关方法
Pthon魔术方法(Magic Methods)-容器相关方法 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.容器相关方法汇总 __len__: 内建函数len(),返回对象的 ...
- Pthon魔术方法(Magic Methods)-运算符重载
Pthon魔术方法(Magic Methods)-运算符重载 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.Python运算符对应的魔术方法 1>.比较运算符 <: ...
随机推荐
- iOS应用笔记之git的本地使用
什么是git (1)什么是git >git是一个 "分布式"的版本号控制工具 >git的作者是Linux之父:Linus Benedict Torvalds,当初开发g ...
- UVa10397_Connect the Campus(最小生成树)(小白书图论专题)
解题报告 题目传送门 题意: 使得学校网络互通的最小花费,一些楼的线路已经有了. 思路: 存在的线路当然全都利用那样花费肯定最小,把存在的线路当成花费0,求最小生成树 #include <ios ...
- LeetCode OJ Basic Calculator II
Basic Calculator II 题目 思路 和这个一样:Basic Calculator I 代码 class ExpressionTransformation { public: strin ...
- iOS Dev (51)加急审核
https://developer.apple.com/appstore/contact/? topic=expedite
- Python笔记---错误笔记
Python---错误笔记 1. Python编码问题: 我们在编写 Python 脚本时,往往会写上中文凝视. 可是有时候,当我们执行程序时.却发现例如以下错误:SyntaxError: Non-A ...
- 1.20 Python基础知识 - python常用模块-1
一.time和datetime 1.time模块 1)time.process_time() >>> import time >>> time.process_ti ...
- jquery模拟可输入的下拉框
//页面html <div id="select" class="select" > <ul> <c:forEach items= ...
- LayoutAnimation-容器动画
1.LayoutAnimation的作用主要就是加载到一个layout上,让这个layout里面的所有控件都有相同的动画效果.现在用到的是在listview中添加动画,使得它每一个item都是滑落显示 ...
- opencv cvPreCornerDetect
关于OpenCv中cvPreCornerDetect 运行出错解决方法 http://m.blog.csdn.net/blog/wode0239 由于书本上示例的不全,相信大家在做的时候,肯定是无从下 ...
- How to Rotate Tomcat catalina.out
If catalina.out becomes 2GB in size, tomcat crashes and fails to start without any error message. To ...