Python dunder
Dunder是 Double UNDERscore
的缩写。指的就是以两个下划线开头和结尾的函数,同时也称作为魔法函数Magic 魔术方法
。这些方法通常不直接调用,而是由解释器调用。
运算符重载魔术方法
魔术方法 |
方法描述 |
__add__ (self, other) |
add operation using + operator |
__sub__ (self, other) |
subtraction operation using - operator. |
__mul__ (self, other) |
multiplication operation using * operator. |
__floordiv__ (self, other) |
floor division operation using // operator. |
__truediv__ (self, other) |
division operation using / operator. |
__mod__ (self, other) |
modulo operation using % operator. |
__pow__ (self, other[, modulo]) |
calculating the power using ** operator. |
__lt__ (self, other) |
comparison using < operator. |
__le__ (self, other) |
comparison using <= operator. |
__eq__ (self, other) |
comparison using == operator. |
__ne__ (self, other) |
comparison using != operator. |
__ge__ (self, other) |
comparison using >= operator. |
示例: __add__
class Test:
def __add__(self,dest):
return self.x + dest.x
def __init__(self):
self.x = 10
def __str__(self):
return str(self.x)
a = Test()
b = Test()
print(a+b)
示例:__ge__
这个方法重载了操作符>=
class Test:
def __add__(self,dest):
return self.x + dest.x
def __init__(self):
self.x = 10
def __str__(self):
return str(self.x)
def __ge__(self,dest):
return self.x >= dest.x
a = Test()
a.x = 15
b = Test()
b.x = 10
print(a>=b)
属性魔法方法
魔术方法 |
方法描述 |
__getattr__ (self, name) |
Is called when the accessing attribute of a class that does not exist. |
__setattr__ (self, name, value) |
Is called when assigning a value to the attribute of a class. |
__delattr__ (self, name) |
Is called when deleting an attribute of a class. |
字符串魔术方法
魔术方法 |
方法描述 |
__str__ (self) |
To get called by built-int str() method to return a string representation of a type. |
__repr__ (self) |
To get called by built-int repr() method to return a machine readable representation of a type. |
__unicode__ (self) |
To get called by built-int unicode() method to return an unicode string of a type. |
__format__ (self,formatstr) |
To get called by built-int string.format() method to return a new style of string. |
__hash__ (self) |
To get called by built-int hash() method to return an integer. |
__nonzero__ (self) |
To get called by built-int bool() method to return True or False. |
__dir__ (self) |
To get called by built-int dir() method to return a list of attributes of a class. |
__sizeof__ (self) |
To get called by built-int sys.getsizeof() method to return the size of an object. |
类型转换魔术方法
魔术方法 |
方法描述 |
__int__ (self) |
To get called by built-int int() method to convert a type to an int. |
__float__ (self) |
To get called by built-int float() method to convert a type to float. |
__complex__ (self) |
To get called by built-int complex() method to convert a type to complex. |
__oct__ (self) |
To get called by built-int oct() method to convert a type to octal. |
__hex__ (self) |
To get called by built-int hex() method to convert a type to hexadecimal. |
__index__ (self) |
To get called on type conversion to an int when the object is used in a slice expression. |
__trunc__ (self) |
To get called from math.trunc() method. |
增加魔术方法
魔术方法 |
方法描述 |
__iadd__ (self, other) |
To get called on addition with assignment e.g. a +=b. |
__isub__ (self, other) |
To get called on subtraction with assignment e.g. a -=b. |
__imul__ (self, other) |
To get called on multiplication with assignment e.g. a *=b. |
__ifloordiv__ (self, other) |
To get called on integer division with assignment e.g. a //=b. |
__idiv__ (self, other) |
To get called on division with assignment e.g. a /=b. |
__itruediv__ (self, other) |
To get called on true division with assignment |
__imod__ (self, other) |
To get called on modulo with assignment e.g. a%=b. |
__ipow__ (self, other) |
To get called on exponents with assignment e.g. a ** =b. |
__ilshift__ (self, other) |
To get called on left bitwise shift with assignment e.g. a<<=b. |
__irshift__ (self, other) |
To get called on right bitwise shift with assignment e.g. a >>=b. |
__iand__ (self, other) |
To get called on bitwise AND with assignment e.g. a&=b. |
__ior__ (self, other) |
To get called on bitwise OR with assignment e.g. a |
__ixor__ (self, other) |
To get called on bitwise XOR with assignment e.g. a ^=b. |
一元魔术方法
魔术方法 |
方法描述 |
__pos__ (self) |
To get called for unary positive e.g. +someobject. |
__neg__ (self) |
To get called for unary negative e.g. -someobject. |
__abs__ (self) |
To get called by built-in abs() function. |
__invert__ (self) |
To get called for inversion using the ~ operator. |
__round__ (self,n) |
To get called by built-in round() function. |
__floor__ (self) |
To get called by built-in math.floor() function. |
__ceil__ (self) |
To get called by built-in math.ceil() function. |
__trunc__ (self) |
To get called by built-in math.trunc() function. |
初始化魔术方法
魔术方法 |
方法描述 |
__new__ (cls, other) |
To get called in an object's instantiation. |
__init__ (self, other) |
To get called by the new method. |
__del__ (self) |
Destructor method. |
属性描述方法
魔术方法 |
方法描述 |
__get__ (self, instance, owner) |
|
__set__ (self, instance, value) |
|
__delete__ |
|
这不是一个好理解的方法。可以借助官方手册进行理解。
示例1:
class Ten:
def __get__(self, obj, objtype=None):
return 10
class A:
x = 5 # Regular class attribute
y = Ten() # Descriptor instance
a = A()
print(a.x) # Normal attribute lookup
# output 5
print(a.y) # Descriptor lookup
# output 10
上下文管理
官方手册
魔术方法 |
方法描述 |
__enter__ (self) |
|
__exit__ (self, *exc) |
|
__aenter__ (self) |
|
__aexit__ (self, *exc) |
|
from contextlib import ContextDecorator
class Context(ContextDecorator):
def __enter__(self):
print("__enter__")
return self
def __exit__(self, *exc):
print("__exit__")
return None
with Context() as c:
print("in context")