2-3 魔法函数一览

还是那句:python的魔法函数都已经提供好了的,我们不能够随便取定义我们的魔法函数。

到底python给我们提供了哪些魔法函数呢?

这边从两个方面来列出python提供给我们的魔法函数:

非数字运算:

(1) - 字符串表示: __repr__, __str__。
(2) - 集合序列相关: __len__, __getitem__, __setitem__, __delitem__, __contains__。
(3) - 迭代相关: __iter__, __next__。
(4) - 可调用:__call__
(5) - 上下文管理器: __enter__, __exit__。
(6) - 数值转换: __abs__, __bool__, __int__, __float__, __hash__, __index__.
(7) - 元类相关: __new__, __init__。
(8) - 属性相关: __getattr__、__setttr__,__getattribute__、__setattribute__, __dir__。
(9) - 属性描述符: __get__、__set__、__delete__。
(10) - 协程:: __await__、 __aiter__、 __anext__、 __aenter__、 __aexit__。

数学运算:

(1) - 一元运算符: __neg__( - 负号)、 __pos__(+ 加号)、__abs__ (绝对值)。
(2) - 二元运算符:__lt__(<)、__le__(<=)、__eq__(==)、__ne__(!=)、__gt__(>)、__ge__(>=)。
(3) - 算术运算符: __add__(+)、__sub__(-)、__mul__()、__truediv__(/)、__floordiv__(//)、__mod__(%)、__divmod__divmod()、__pow__*或pow()、__round__round()。
(4) - 反向算术运算符: __radd__、__rsub__、__rmul__、__rtruediv__、__rfloordiv__、__rmod__、__rdivmod__、__rpow__。
(5) - 增量赋值算术运算符: __iadd__、__isub__、__imul__、__itruediv__、__ifloordiv__、__imod__、__ipow__。
(6) - 位运算符: __invert__(~)、__lshift__(<<)、__rshift__(>>)、__and__(&)、__or__(|)、__xor__(^)。
(7) - 反向位运算符: __rlshift__、__rrshift__、__rand__、__rxor__、__ror__。
(8) - 增量赋值位运算符: __ilshift__、__irshift__、__iand__、__ixor__、__ior__。


下面我们来接介绍两个魔法函数,关于字符串的__str__与__repr__:
__str__:作为实例对象在输出时的返回,看如下代码。

# 未声明时
class Company:
    def __init__(self, employee_list):
        self.employee = employee_list


company = Company(['tom', 'bob', 'jane'])
print(company)

当我们定义了他的输出返回__str__:

class Company:
    def __init__(self, employee_list):
        self.employee = employee_list

    def __str__(self):
        return '-'.join(self.employee)

company = Company(['tom', 'bob', 'jane'])
print(company)

__repr__: 用于开发模式,比如在ipython、jupyternotebook的环境下,直接访问变量得到的返回形式,对比如下:

2-3 魔法函数一览_第1张图片

你可能感兴趣的:(2-3 魔法函数一览)