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__

 

转载于:https://www.cnblogs.com/ArvinZhao/p/9635687.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值