Fork me on GitHub

Python高级语法:魔法函数

介绍的魔法函数有(持续更新): __ init__()、__ str__()、__ new__()、__ unicode__()、 __ call__()、 __ len__()、 __repr__()、__ setattr__()、 __ getattr__()、 __ getattribute__()、 __ delattr__()、__ setitem__()、 __ getitem__()、__ delitem__()、 __ iter__()、__ del__()、 __dir__()、__dict__()、__exit__(),__enter(), __all__()等函数。

1. 前言

1.1 什么是魔法函数?

魔法函数一览

所谓魔法函数(Magic Methods),是Python的一种高级语法,允许你在类中自定义函数(函数名格式一般为__xx__),并绑定到类的特殊方法中。比如在类A中自定义__str__()函数,则在调用str(A())时,会自动调用__str__()函数,并返回相应的结果。在我们平时的使用中,可能经常使用__init__函数(构造函数)和__del__函数(析构函数),其实这也是魔法函数的一种。

  • Python中以双下划线(__xx__)开始和结束的函数(不可自己定义)为魔法函数。
  • 调用类实例化的对象的方法时自动调用魔法函数。
  • 在自己定义的类中,可以实现之前的内置函数。

1.2 魔法函数有什么作用?

魔法函数可以为你写的类增加一些额外功能,方便使用者理解。举个简单的例子,我们定义一个“人”的类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实例时自动调用。

2. 常见的魔法函数

我们将魔法方法分为:非数学运算和数学运算两大类。

2.1 非数学运算

2.1.1 字符串表示

__repr__函数和__str__函数:

初识CV:字符串表示:__repr__函数和__str__函数:​zhuanlan.zhihu.com

2.1.2 集合、序列相关

__len__函数、__getitem__函数、__setitem__函数、__delitem__函数和__contains__函数:

初识CV:集合、序列相关:__len__函数、__getitem__函数、__setitem__函数、__delitem__函数和__contains__函数​zhuanlan.zhihu.com

2.1.3 迭代相关

__iter__函数和__next__函数:

初识CV:迭代相关:__iter__函数和__next__函数​zhuanlan.zhihu.com

2.1.4 可调用

__call__函数:

初识CV:可调用:__call__函数​zhuanlan.zhihu.com

2.1.5 with上下文管理器

__enter__函数和__exit__函数:

初识CV:with上下文管理器:__enter__函数和__exit__函数​zhuanlan.zhihu.com

2.1.6 数值转换

__abs__函数、__bool__函数、__int__函数、__float__函数、__hash__函数和__index__函数:

2.1.7 元类相关

__new__函数和__init__函数:

初识CV:元类相关:__new__函数和__init__函数​zhuanlan.zhihu.com

2.1.8 属性相关

__getattr__函数、__setattr__函数、__getattribute__函数、__setattribute__函数和__dir__函数:

初识CV:属性相关:__getattr__函数、__setattr__函数、__getattribute__函数、__setattribute__函数和__dir__函数:​zhuanlan.zhihu.com

2.1.9 属性描述符

__get__函数、__set__函数和__delete_函数:

初识CV:属性描述符:__get__函数、__set__函数和__delete_函数​zhuanlan.zhihu.com

 

2.1.10 协程

__await__函数、__aiter__函数、__anext__函数、__aenter__函数和__aexit__函数

2.2 数学运算

2.2.1 一元运算符

__neg__ (-)、__pos__ (+)和__abs__函数。

2.2.2 二元运算符

__lt__ (<)、__le__ (<=)、__eq__ (==)、__ne__ (!=)、__gt__ (>)和__ge__ (>=)。

2.2.3 算术运算符

__add__ (+)、__sub__ (-)、__mul__ (*)、__truediv__ (/)、__floordiv__ (//)、__mod__ (%)、__divmod__ 或divmod()、__pow__ 或pow() (**)和__round__ 或round()。

2.2.4 反向算术运算符

__radd__、__rsub__、__rmul__、__rtruediv__、__rfloordiv__、__rmod__、__rdivmod__和__rpow__。

2.2.5 增量赋值算术运算符

__iadd__、__isub__、__imul__、__ifloordiv__和__ipow__。

2.2.6 位运算符

__invert__ (~)、__lshift__ (<<)、__rshift__ (>>)、__and__ (&)、__or__ (|)和__xor__ (^)。

2.2.7 反向位运算符

__rlshift__、__rrshift__、__iand__、__ixor__和__ior__。

2.2.8 增量赋值运算符

__ilshift__、__irshift__、__iand__、__ixor__和__ior__。

2.3 其他魔法函数

__ unicode__()函数,__ delattr__()函数, __ del__()函数, __dict__()函数,__all__()函数:

初识CV:其他魔法函数:__ unicode__(),__ delattr__(), __ del__(), __dict__(),__all__()​zhuanlan.zhihu.com

[1][2][3][4]

 

参考

  1. ^Python类特殊成员(属性和方法) http://c.biancheng.net/view/2367.html
  2. ^Python中内建属性__getattribute__的用法总结 https://blog.csdn.net/yitiaodashu/article/details/78974596
  3. ^Python3基础 __delattr__ 在一个属性被删除时的行为 https://www.cnblogs.com/xingchuxin/p/10425683.html
  4. ^Python __exit__,__enter__函数with语句的组合应用 http://blog.sina.com.cn/s/blog_13cc013b50102wvp1.html
编辑于 05-29
原文链接:https://zhuanlan.zhihu.com/p/344951719
posted @ 2021-06-18 16:05  stardsd  阅读(822)  评论(0编辑  收藏  举报