在 Python 中,运算符是如何映射到魔法方法的?
在这篇文章中,我们将向您解释 Python 中的运算符是如何映射到魔法方法的。
Python 的魔法方法是特殊的以双下划线开头和结尾的方法。它们也被称为dunder方法。魔法方法不打算由您直接调用,而是由类在特定操作时调用。当您使用 + 运算符添加两个数字时,__add__()方法会在内部被调用。
Python 中的许多魔法方法都由内置类定义。要获取类继承的魔法方法的数量,请使用dir()函数。
示例
以下程序列出了在int 类中定义的所有属性和方法。
print(dir(int))
输出
执行后,上述程序将生成以下输出:
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
这里int类包含许多用双下划线括起来的魔法方法。
__add__ 方法
__add__ 方法是一个魔法方法,当我们使用+ 运算符添加两个值时会调用它。1. 在 Python 中,运算符是如何映射到魔法方法的?
示例
以下程序使用魔法方法的__add__方法运算符返回给定值加上一个值的和:
n = 20 # adding 10 to input number using + sign print("Addition using + sign:", n + 10) # adding 10 to input number using __add__ method # by passing the value to be added as an argument print("Addition using __add__ method:", n.__add__(10))
输出
执行后,上述程序将生成以下输出:
Addition using + sign: 30 Addition using __add__ method: 30
如您所见,当您输入 n+10 时,+ 运算符会调用__add__(10)方法。您也可以显式调用n.__add__(10)来获得相同的结果。但是,如前所述,魔法方法并非设计为直接调用,而是通过其他方法或操作间接调用。
在 Python 中,魔法方法最常用于定义预定义运算符的重载行为。例如,算术运算符默认情况下对数字操作数进行运算。这意味着必须将数字对象与 +、-、*、/ 等运算符结合使用。在字符串、列表和元组类中,+ 运算符也被指定为连接运算符。+ 运算符被称为重载。
要在您自己的自定义类中使用重载行为,请覆盖相应的魔法方法。例如,要使用自定义类的对象使用 + 运算符,它必须包含__add__()方法。
__new__() 方法
要创建类的新的实例,Java 和 C# 等语言使用 new 运算符。__new__()魔法方法在 Python 中会在__init__()方法之前隐式调用。__new__()方法返回一个新对象,随后使用__init__()方法对其进行初始化。
示例
# defining a class class Tutorialspoint: def __new__(democlass): print ("calling __new__ magic method") instance = object.__new__(democlass) return instance def __init__(self): print ("calling __init__ magic method") self.author ='XYZ' # calling the above-defined Tutorialspoint class result = Tutorialspoint()
输出
执行后,上述程序将生成以下输出:
calling __new__ magic method calling __init__ magic method
当您创建Tutorialspoint类的实例时,您将获得上述结果。
因此,__new__()方法在__init__()方法之前被调用。
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
__str__() 方法
__str__()是另一个重要的魔法方法。它被重写以返回任何用户定义类的可打印字符串表示形式。我们已经看到了内置函数str(),它从作为参数传递的对象返回一个字符串。
示例
# input number n = 10 # printing the string form of a number using str() print(str(n)) # printing the string form of a number using __str__() magic method # Both are equivalent print(int.__str__(n))
输出
执行后,上述程序将生成以下输出:
10 10
这里str(10)返回值“10”。调用时,它会调用 int 类的__str__()方法。
并且str()函数在内部调用在类中定义的__str__()方法。因此它被称为魔法方法!
重要的魔法方法
下表列出了 Python 3 中最重要的魔法方法。
初始化和构造 | 描述 |
---|---|
__new__(cls, other) | 在对象实例化时调用。 |
__init__(self, other) | 由 __new__ 方法调用。 |
__del__(self) | 析构方法。 |
一元运算符和函数 | 描述 |
---|---|
__pos__(self) | 对一元正数调用,例如:+someobject。 |
__neg__(self) | 对一元负数调用,例如:-someobject。 |
__abs__(self) | 由内置 abs() 函数调用。 |
__invert__(self) | 使用 ~ 运算符进行反转时调用。 |
__round__(self,n) | 由内置 round() 函数调用。 |
__floor__(self) | 由内置 math.floor() 函数调用。 |
__ceil__(self) | 由内置 math.ceil() 函数调用。 |
__trunc__(self) | 由内置 math.trunc() 函数调用。 |
增强赋值 | 描述 |
---|---|
__iadd__(self, other) | 在带有赋值的加法运算中调用,例如:a +=b。 |
__isub__(self, other) | 在带有赋值的减法运算中调用,例如:a -=b。 |
__imul__(self, other) | 在带有赋值的乘法运算中调用,例如:a *=b。 |
__ifloordiv__(self, other) | 在带有赋值的整数除法运算中调用,例如:a //=b。 |
__idiv__(self, other) | 在带有赋值的除法运算中调用,例如:a /=b。 |
__itruediv__(self, other) | 在带有赋值的真除法运算中调用 |
__imod__(self, other) | 在带有赋值的取模运算中调用,例如:a%=b。 |
__ipow__(self, other) | 在带有赋值的指数运算中调用,例如:a **=b。 |
__ilshift__(self, other) | 在带有赋值的左移位运算中调用,例如:a<<=b。 |
__irshift__(self, other) | 在带有赋值的右移位运算中调用,例如:a >>=b。 |
__iand__(self, other) | 在带有赋值的按位与运算中调用,例如:a&=b。 |
__ior__(self, other) | 在带有赋值的按位或运算中调用,例如:a|=b。 |
__ixor__(self, other) | 在带有赋值的按位异或运算中调用,例如:a ^=b。 |
类似地,我们还有许多其他魔法方法,如类型转换魔法方法、字符串魔法方法、属性魔法方法、运算符魔法方法等 - 链接
结论
通过示例,我们在这篇文章中了解了一些映射到魔法方法的运算符。在这篇文章中,我们学习了魔法方法及其用法,以及魔法方法的一些运算符。