美文网首页
Python 魔术方法(Magic Methods)

Python 魔术方法(Magic Methods)

作者: SingleDiego | 来源:发表于2020-03-23 22:29 被阅读0次

参考资料:




用于比较的魔术方法

__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)

    参考资料: https://pycoders-weekly-chinese.readthedocs.io/en/l...

  • 魔术方法 Python's Magic Methods

    构建和初始化 __new__(cls,[...)一个对象的实例化时 __new__ 是第一个被调用的方法。在类中传...

  • Python 魔术方法(Magic Methods)- 2

    参考资料:https://rszalski.github.io/magicmethods/#access __ge...

  • PHP魔术方法

    魔术方法(Magic methods) PHP中把以两个下划线__开头的方法称为魔术方法,这些方法在PHP中充当了...

  • Python类-magic methods魔术方法, since

    (2022.04.19-20 Tues-Wed)Python中的魔术方法,是可以定义在类中的特殊方法,可在特定的情...

  • php魔术方法

    PHP 中被称为魔术方法(Magic methods)。在命名自己的类方法时不能使用这些方法名,除非是想使用其魔术...

  • PHP 魔术方法

    前言PHP中把以两个下划线__开头的方法称为魔术方法(Magic methods),这些方法在PHP中充当了举足轻...

  • PHP魔术方法

    PHP中把以两个下划线__开头的方法称为魔术方法(Magic methods),这些方法在PHP中充当了举足轻重的...

  • Dunder methods & operator overlo

    link:https://www.python-course.eu/python3_magic_methods.p...

  • 流畅的Python

    第一章 Python数据模型魔术方法(magic method)或者说双下方法(dunder method)表示特...

网友评论

      本文标题:Python 魔术方法(Magic Methods)

      本文链接:https://www.haomeiwen.com/subject/funiyhtx.html