Skip to content

Instantly share code, notes, and snippets.

@RagtagGeoduck
Last active February 20, 2021 03:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RagtagGeoduck/c172f7853bfaa1af0be364ee990e14ba to your computer and use it in GitHub Desktop.
Save RagtagGeoduck/c172f7853bfaa1af0be364ee990e14ba to your computer and use it in GitHub Desktop.
"""
普通算数操作符
现在我们仅仅覆盖了普通的二进制操作符:+,-,*和类似符号。这些符号大部分来说都浅显易懂。
__add__(self, other) 实现加法。
__sub__(self, other) 实现减法。
__mul__(self, other) 实现乘法。
__floordiv__(self, other) 实现 // 符号实现的整数除法。
__div__(self, other) 实现 / 符号实现的除法。
__truediv__(self, other) 实现真除法。
注意只有只用了 from __future__ import division 的时候才会起作用。
__mod__(self, other) 实现取模算法 %
__divmod___(self, other) 实现内置 divmod() 算法
__pow__ 实现使用 ** 的指数运算
__lshift__(self, other) 实现使用 << 的按位左移动
__rshift__(self, other) 实现使用 >> 的按位左移动
__and__(self, other) 实现使用 & 的按位与
__or__(self, other) 实现使用 | 的按位或
__xor__(self, other) 实现使用 ^ 的按位异或
"""
反运算
下面我将会讲解一些反运算的知识。有些概念你可能会认为恐慌或者是陌生。但是实际上非常简单。以下是一个例子:
some_object + other
这是一个普通的加法运算,反运算是相同的,只是把操作数调换了位置:
other + some_object
所以,除了当与其他对象操作的时候自己会成为第二个操作数之外,所有的这些魔术方法都与普通的操作是相同的。大多数情况下,反运算的结果是与普通运算相同的。所以你可以你可以将 __radd__ 与 __add__ 等价。
__radd__(self, other) 实现反加
__rsub__(self, other) 实现反减
__rmul__(self, other) 实现反乘
__rfloordiv__(self, other) 实现 // 符号的反除
__rdiv__(self, other) 实现 / 符号的反除
__rtruediv__(self, other) 实现反真除,只有当 from __future__ import division 的时候会起作用
__rmod__(self, other) 实现 % 符号的反取模运算
__rdivmod__(self, other) 当 divmod(other, self) 被调用时,实现内置 divmod() 的反运算
__rpow__ 实现 ** 符号的反运算
__rlshift__(self, other) 实现 << 符号的反左位移
__rrshift__(self, other) 实现 >> 符号的反右位移
__rand__(self, other) 实现 & 符号的反与运算
__ror__(self, other) 实现 | 符号的反或运算
__xor__(self, other) 实现 ^ 符号的反异或运算
__eq__(self, other) 定义了等号的行为, == 。
__ne__(self, other) 定义了不等号的行为, != 。
__lt__(self, other) 定义了小于号的行为, < 。
__gt__(self, other) 定义了大于等于号的行为, > 。
__ge__(self, other) >=
__le__(self, other) <=
_iadd(self, other) +=;增量赋值
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment