1. 程式人生 > >A Guide to Python's Magic Methods

A Guide to Python's Magic Methods

取整 存在 mean control rev 取余 gui rsh iterator

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__:

A Guide to Python's Magic Methods