介绍的魔法函数有(持续更新): __ init__()、__ str__()、__ new__()、__ unicode__()、 __ call__()、 __ len__()、 __repr__()、__ setattr__()、 __ getattr__()、 __ getattribute__()、 __ delattr__()、__ setitem__()、 __ getitem__()、__ delitem__()、 __ iter__()、__ del__()、 __dir__()、__dict__()、__exit__(),__enter(), __all__()等函数。
所谓魔法函数(Magic Methods),是Python的一种高级语法,允许你在类中自定义函数(函数名格式一般为__xx__),并绑定到类的特殊方法中。比如在类A中自定义__str__()函数,则在调用str(A())时,会自动调用__str__()函数,并返回相应的结果。在我们平时的使用中,可能经常使用__init__函数(构造函数)和__del__函数(析构函数),其实这也是魔法函数的一种。
魔法函数可以为你写的类增加一些额外功能,方便使用者理解。举个简单的例子,我们定义一个“人”的类People,当中有属性姓名name、年龄age。让你需要利用sorted函数对一个People的数组进行排序,排序规则是按照name和age同时排序,即name不同时比较name,相同时比较age。由于People类本身不具有比较功能,所以需要自定义,你可以这么定义People类:
class People(object): def __init__(self, name, age): self.name = name self.age = age return def __str__(self): return self.name + ":" + str(self.age) def __lt__(self, other): return self.name < other.name if self.name != other.name else self.age < other.age if __name__=="__main__": print("\t".join([str(item) for item in sorted([People("abc", 18), People("abe", 19), People("abe", 12), People("abc", 17)])]))
输出结果:
abc:17 abc:18 abe:12 abe:19
上个例子中的__lt__函数即less than函数,即当比较两个People实例时自动调用。
我们将魔法方法分为:非数学运算和数学运算两大类。
__repr__函数和__str__函数:
初识CV:字符串表示:__repr__函数和__str__函数:25 赞同 · 12 评论文章
__len__函数、__getitem__函数、__setitem__函数、__delitem__函数和__contains__函数:
初识CV:集合、序列相关:__len__函数、__getitem__函数、__setitem__函数、__delitem__函数和__contains__函数18 赞同 · 8 评论文章
__iter__函数和__next__函数:
初识CV:迭代相关:__iter__函数和__next__函数21 赞同 · 0 评论文章
__call__函数:
初识CV:可调用:__call__函数24 赞同 · 2 评论文章
__enter__函数和__exit__函数:
初识CV:with上下文管理器:__enter__函数和__exit__函数10 赞同 · 0 评论文章
__abs__函数、__bool__函数、__int__函数、__float__函数、__hash__函数和__index__函数:
__new__函数和__init__函数:
初识CV:元类相关:__new__函数和__init__函数13 赞同 · 1 评论文章
__getattr__函数、__setattr__函数、__getattribute__函数、__setattribute__函数和__dir__函数:
初识CV:属性相关:__getattr__函数、__setattr__函数、__getattribute__函数、__setattribute__函数和__dir__函数:10 赞同 · 0 评论文章
__get__函数、__set__函数和__delete_函数:
初识CV:属性描述符:__get__函数、__set__函数和__delete_函数11 赞同 · 1 评论文章
__await__函数、__aiter__函数、__anext__函数、__aenter__函数和__aexit__函数
__neg__ (-)、__pos__ (+)和__abs__函数。
__lt__ (<)、__le__ (<=)、__eq__ (==)、__ne__ (!=)、__gt__ (>)和__ge__ (>=)。
__add__ (+)、__sub__ (-)、__mul__ (*)、__truediv__ (/)、__floordiv__ (//)、__mod__ (%)、__divmod__ 或divmod()、__pow__ 或pow() (**)和__round__ 或round()。
__radd__、__rsub__、__rmul__、__rtruediv__、__rfloordiv__、__rmod__、__rdivmod__和__rpow__。
__iadd__、__isub__、__imul__、__ifloordiv__和__ipow__。
__invert__ (~)、__lshift__ (<<)、__rshift__ (>>)、__and__ (&)、__or__ (|)和__xor__ (^)。
__rlshift__、__rrshift__、__iand__、__ixor__和__ior__。
__ilshift__、__irshift__、__iand__、__ixor__和__ior__。
__ unicode__()函数,__ delattr__()函数, __ del__()函数, __dict__()函数,__all__()函数: