Python 魔术方法(Magic Methods)

参考资料:

  • https://pycoders-weekly-chinese.readthedocs.io/en/latest/issue6/a-guide-to-pythons-magic-methods.html

  • https://rszalski.github.io/magicmethods/

  • https://www.cnblogs.com/zhouyixian/p/11129347.html




用于比较的魔术方法

__eq__(self, other) 定义了等号的行为,==

__ne__(self, other) 定义了不等号的行为,!=

__lt__(self, other) 定义了小于号的行为,<

__gt__(self, other) 定义了大于号的行为,>

__le__(self, other) 定义了小于等于号的行为,<=

__ge__(self, other) 定义了大于等于号的行为,>=

例子:

class People:

    def __init__(self, age):
        self.age = age

    # 定义了等号的行为
    def __eq__(self, other):
        return self.age == other.age

    # 定义了不等号的行为
    def __ne__(self, other):
        return self.age != other.age
    
    # 定义了小于号的行为
    def __lt__(self, other):
        return self.age < other.age
    
    # 定义了大于号的行为
    def __gt__(self, other):
        return self.age > other.age

    # 定义了小于等于号的行为
    def __le__(self, other):
        return self.age <= other.age
    
    # 定义了大于等于号的行为
    def __gt__(self, other):
        return self.age >= other.age

tom = People(18)
sam = People(18)
lucy = People(19)

print(tom >= sam)
>>> True




用于数值处理的魔术方法

1. 一元操作符和函数

__pos__(self) 实现正号的特性(比如 +some_object

__neg__(self) 实现负号的特性(比如 -some_object

__abs__(self) 实现内置 abs() 函数(绝对值)的特性

__invert__(self) 实现 ~ 操作符(取反运算)的特性

__round__(self, n) 实现内置 round() 函数的行为,n 是要四舍五入的小数位数

__floor__(self) 实现 math.floor() 函数的行为,即向下舍入到最接近的整数

__ceil__(self) 实现 math.ceil() 函数的行为,即四舍五入到最接近的整数

__trunc__(self) 实现 math.trunc() 函数的行文,即只截取整数部分

2. 普通算术符号

__add__(self, other) 实现加法

__sub__(self, other) 实现减法

__mul__(self, other) 实现乘法

__floordiv__(self, other) 实现 // 运算符实现整数除法

__div__(self, other) 实现 / 运算符实现除法

__truediv__(self, other) 实现 true division。请注意,这仅 from __future__ import division 在生效时有效

__mod__(self, other) 实现 % 运算符实现取余运算

__divmod__(self, other) 实现 divmod() 内置函数,返回结果包含除数和余数

__pow__ 实现 ** 运算符实现指数的行为

__lshift__(self, other) 实现 << 运算符,按位左移

__rshift__(self, other) 实现 >> 运算符,按位右移

__and__(self, other) 实现 & 运算符,即 and 操作符

__or__(self, other) 实现 | 运算符,即 or 操作符

__xor__(self, other) 实现 ^ 运算符,即 is not 操作符

你可能感兴趣的:(Python 魔术方法(Magic Methods))