<> What is magic method ?

Magic method (magic methods):python The magic method in refers to a method whose name begins with two underscores and ends with two underscores , So it is also called Dunder Methods
(Double
Underscores). Commonly used for operator overloading . The magic method will be automatically called by the back end when performing an operation on a class , You don't need to call directly . For example, when using + When adding two numbers , Will be called inside the class __add__() method , Another example is to create a class A Object of ,a=A(),python Will be called automatically __new__ and __init__.

<> Common magic methods

<> Initialization and construction

Method name Description
_new_(cls, other) Called when instantiating an object
_init_(self, other) Used to initialize objects , cover __new__ Method call
_del_(self) Method of object destruction
There are several problems that need attention :

* Inheritance only object There are new types of _new_
* __new__ At least one parameter cls, Represents the current class
* __new__ Must have a return value , Return the created object
* __init__ There must be a parameter self, This is __new__ Return value of , __init__ No return value is required
Test code :
class MyClass(object): def __init__(self, num): self.num = num print("i am
__init__ function") def __new__(cls, num): print("i am __new__ function") obj =
super(MyClass, cls).__new__(cls) return obj def __del__(self): print("i am
__del__ function") myclass = MyClass(num=55) print("create obj ok === ") del
myclass
Output results :
i am __new__ function i am __init__ function create obj ok === i am __del__
function
<> unary operator

Method name Description
_pos_(self) Will be called by the positive operator , for example +a
_neg_(self) Will be called by the negation operator , for example -a
_abs_(self) Calling built-in functions abs() Called when , Take absolute value
_invert_(self) in use ~ Operator is called , Bitwise inversion
_round_(self, n) Execute built-in functions round() Called when , Round to the nearest ,n Is the number of decimal places
_floor_(self) Execute built-in functions math.floor() Called when , Take the maximum integer less than or equal to this value
_ceil_(self) Execute built-in functions math.ceil() Called when , Take the smallest integer greater than or equal to this value
_trunc_(self) implement math.trunc() Called when function , Take the truncated integer of this value
Test code :
class TestUnaryOpsAndFunc: def __init__(self, num=0) -> None: self._num = 3
self._neg_num = -5 self._float_num = 3.1415 self._neg_float_num = -3.1415 def
__pos__(self): return +self._neg_num def __neg__(self): return -self._num def
__abs__(self): return abs(self._neg_float_num) def __invert__(self): return ~
self._num def __round__(self): return round(self._float_num) def __floor__(self)
: return math.floor(self._neg_float_num) def __ceil__(self): return math.ceil(
self._float_num) def __trunc__(self): return math.trunc(self._float_num)
test_class= TestUnaryOpsAndFunc() print("pos: ", +test_class) print("neg: ", -
test_class) print("abs: ", abs(test_class)) print("invert: ", ~test_class) print
("round: ", round(test_class)) print("floor: ", math.floor(test_class)) print(
"ceil: ", math.ceil(test_class)) print("trunc: ", math.trunc(test_class))
test result :
pos: -5 neg: -3 abs: 3.1415 invert: -4 round: 3 floor: -4 ceil: 4 trunc: 3
<> augmented assignment

Method name Description
_iadd_(self, other) Called when performing incremental addition assignment , for example : a += b
_isub_(self, other) Called when performing subtraction increment assignment , for example : a -= b
_imul_(self, other) Called when performing incremental assignment of multiplication , for example : a *= b
_ifloordiv_(self, other) Called when performing incremental assignment of integer division , for example : a //= b, Result rounded down
_idiv_(self, other) Called when performing division incremental assignment , for example : a /= b
_itruediv_(self, other) Called when the real division incremental assignment is performed
_imod_(self, other) Called when performing residual incremental assignment , for example : a %= b
_ipow_(self, other) Called when performing power increment assignment , for example : a **= b
_ilshift_(self, other) Called when the left shift increment assignment is performed , for example : a <<= b
_irshift_(self, other) Called when performing a shift right incremental assignment , for example : a >>= b
_iand_(self, other) Called when performing bitwise and incremental assignment , for example : a &= b
_ior_(self, other) Called when performing bitwise or incremental assignment , for example : a
_ixor_(self, other) Called when performing bitwise exclusive or incremental assignment , for example : a ^= b
<> Type conversion

Method name Description
_init_(self) Built in method int() call , To convert a type to int
_long_(self) Built in method long() call , To convert a type to long
_float_(self) Built in method float() call , To convert a type to float
_complex_(self) Built in method complex() call , To convert a type to complex
_oct_(self) Built in method oct() call , To convert a type to octal, That is, convert an object to octal
_hex_(self) Built in method hex() call , To convert a type to hexadecimal, That is, convert an object to hexadecimal
_index_(self) When objects are used to represent slices , Will call this function to convert to int type
_trunc_(self) implement math.trunc() Method is called when , Take the truncated integer of this value
<> String correlation

Method name Description
_str_(self) Built in method str() call , Returns a string describing the type
_repr_(self) Built in method repr() Called when the parameter of , Returns a machine readable representation , Machine readable means that the return value can be executed on the command line
_unicode_(self) Built in method unicode() call , Return one unicode String of
_format_(self,formatstr) Built in method string.fromat() call , Returns a new format string , for example : “name:
{0}”.format(a), Will call xxxxxxxxx
_hash_(self) Built in method hash() call , Returns an integer number
_nonzero_(self) Built in method bool() call , return True or False, stay python3 Rename to _bool_
_dir_(self) Built in method dir() call , Returns a list of properties of a class
_sizeof_(self) Built in method sys.getsizeof() call , Returns the size of an object
str and repr I will write a separate article to introduce the difference between

Test code :
class Person: def __init__(self, name, age) -> None: self._name = name self.
_age= age def __str__(self) -> str: output = "str called,name: {0}; age: {1}".
format(self._name, self._age) return output def __repr__(self) -> str: output =
"repr called, name: {0}; age: {1}".format(self._name, self._age) return output
person= Person(name="william", age=24) print(person) print(repr(person))
test result :
str called,name: william; age: 24 repr called, name: william; age: 24
<> Attribute correlation

Method name Description
_getattr_(self, name) Called when accessing a property that does not exist in the class
_setattr_(self, name, value) Called when a property of a class is assigned a value
_getattribute_(self, name) Called when accessing a property that does not exist in the class , Priority call
_setattribute_(self, name) Called when accessing a property that does not exist in the class , Priority call
_delattr_(self, name) Called when deleting a class's attribute
_dir_(self) Built in method dir() call , Returns a list of properties of a class
<> descriptor

To create a descriptor , This class must implement _get_, _set_, __delete__ At least one of the three methods

Method name Description
_get_(self, instance, owner) Called when getting property value
_set_(self, instance, value) Called when setting property value
_delete_(self, instance, owner) Called when deleting a property value
Test code :
class Attribute: def __init__(self, data) -> None: self._data = data def
__get__(self, instance, owner): print("__get__ called") return self._data def
__set__(self, instance, value): print("__set__ called") self._data = value def
__delete__(self, instance): print("__delete__ called") del self._data class
MyClass: attr = Attribute(99) def __init__(self, attr="defaule value"): self.
attr= attr myclass = MyClass() myclass.attr = "new value" value = myclass.attr
print("value: ", value) del myclass.attr #value = myclass._attr #print("value:
", value) myclass1 = MyClass() value = myclass1.attr print("value: ", value)
test result :
__set__ called __set__ called __get__ called value: new value __delete__
called __set__ called __get__ called value: defaule value
<> Copy

Method name Description
_copy_(self) cover copy.copy() call , Returns a shallow copy of an object , The data contained in a new instance is a reference
_deepcopy_(self, memodict) cover copy.deepcopy() call , Returns a deep copy of an object , One copy of all object data
<> Synergetic process

Method name Description
_await_(self) realization __await__ Class of method , The constructed object is awaitbale of , Returns an iterator for await Method use
_aiter_(self) Asynchronous iterator async for Used in , Returns an asynchronous iterator object , Also self
_anext_(self) An asynchronous iterator Must be achieved __anext__ method , return awaitbale
_aenter_(self) Asynchronous context manager async with, Call on entry
_aexit_(self) Asynchronous context manager async with, Called on exit
Test code
class Awaitable: def __init__(self) -> None: self._person = [] p = Person(name=
"william", age=24) p1 = Person(name="william1", age=25) p2 = Person(name=
"william2", age=26) p3 = Person(name="william3", age=27) self._person.append(p)
self._person.append(p1) self._person.append(p2) self._person.append(p3) def
__aiter__(self): print("aiter called ...") self.index = 0 return self async def
__anext__(self): print("anext called") while self.index < len(self._person):
self.index += 1 return self._person[self.index - 1] raise StopAsyncIteration
async def AsyncFunction(): print("called async function") return 1 async def
test_coroutine(): func = AsyncFunction() await func async def test_async_context
(): async with AsyncContext() as ac: print("main block") async def
test_async_for(): async for a in Awaitable(): print("a: ", a) asyncio.run(
test_coroutine()) asyncio.run(test_async_for()) asyncio.run(test_async_context()
)
test result :
called async function aiter called ... anext called a: str called,name: william
; age: 24 anext called a: str called,name: william1; age: 25 anext called a: str
called,name: william2; age: 26 anext called a: str called,name: william3; age:
27 anext called enter the block main block exit the block
<> Binary operator

Method name Description
_add_(self, other) When used + Called when performing an addition operation
_sub_(self, other) When used - Called when performing subtraction
_mul_(self, other) When used * Called when performing multiplication
_div_(self, other) When used / Called when performing division
_floordiv_(self, other) When used // Called when performing rounding and division
_truediv_(self, other) When used / Called when performing division , only from _future_ import division It only works when
_mod_(self, other) When used % Called when performing the remainder operation
_pow_(self, other[,modulo]) When used ** Called when performing a power operation
_lshift_(self, other) When used << Called when performing a left shift operation
_rshift_(self, other) When used >> Called when performing the shift right operation
_and_(self, other) When used & Called when performing bitwise and operations
_xor_(self, other) When used ^ Called when performing bitwise XOR operation
_or_(self, other) When used | Called when performing bitwise or operations
_lt_(self, other) When used < Called when the operator is compared
_le_(self, other) When used <= Called when the operator is compared
_eq_(self, other) When used == Called when the operator is compared
_ne_(self, other) When used != Called when the operator is compared
_ge_(self, other) When used >= Called when the operator is compared
<> Reflection arithmetic operator

What is reflection operation ? such as : a + b, Reflection means exchanging the positions of two operands : b + a, Pay attention at this time b It must not be possible to define non reflective operations ,
Only in this way can we call a Reflection operation of _radd()_

Method name Description
_radd_(self, other) When used + Called when performing reflection addition
_rsub_(self, other) When used - Called when performing reflection subtraction
_rmul_(self, other) When used * Called when performing reflection multiplication
_rfloordiv_(self, other) When used // Called when performing reflection rounding and division
_rtruediv_(self, other) When used / Called when performing reflection Division
_rmod_(self, other) When used % Called when performing reflection remainder operation
_rpow_(self, other[,modulo]) When used ** Called when performing reflection power operation
_rlshift_(self, other) When used << Called when the reflection shift left operation is performed
_rrshift_(self, other) When used >> Called when the reflection shift right operation is performed , Need to reconfirm
_rand_(self, other) When used & Called when performing bitwise and operations
_rxor_(self, other) When used ^ Called when performing bitwise XOR operation
_ror_(self, other) When used | Called when performing bitwise or operations
<> Set correlation

Method name Description
_len_(self) Built in method len() call , Returns the length of the container , Both variable and immutable container types need to be implemented
_getitem_(self, key) in use key Called when accessing members , object[key]
_setitem_(self, key, value) In the set key Called when value is assigned , object[key] = value
_delitem_(self, key) cover del call , for example : del object[key]
_contains_(self) In execution in() perhaps not in Called when
_reversed_(self) Built in method reversed() call , Flip sequence order ,
_missing_(self) Used in subclasses of dictionaries , When trying to access a that does not exist in the dictionary key Called when
<> Iterative correlation

Method name Description
_iter_(self) Built in method iter() Call or for item in container Call when , To be in __iter__ in return self
_next_(self)
Test code :
class MyQueue: def __init__(self) -> None: self._queue = [i for i in range(10)]
def __iter__(self): self._index = 0 return self def __next__(self): while self.
_index< len(self._queue) - 1: self._index += 1 return self._queue[self._index]
raise StopIteration it = iter(MyQueue()) while True: try: num = next(it) print(
"num: ", num) except StopIteration: print("visit finished") break num: 1 num: 2
num: 3 num: 4 num: 5 num: 6 num: 7 num: 8 num: 9 visit finished
<> call

Method name Description
_call_(self) Enable class objects to be called like functions , object()
Test code :
class Dog: def __init__(self, color) -> None: self._color = color def __call__(
self, *args: Any, **kwds: Any) -> Any: return self._color dog = Dog(color=
"black") color = dog() print("color: ", color)
test result :
color: black
<> Context manager

Method name Description
_enter_(self) What the context manager should do at first , __enter__ The return value of will be assigned to as Objects behind
_exit_(self, exception_type, exception_value, traceback) What to do when exiting the statement block
Test code :
class MyContex: def __enter__(self): print ("enter the closer") def __exit__(
self, exception_type, exception_value, traceback): print("exit the closer") with
MyContex() as context: print("it is in closer")
test result :
enter the closer it is in closer exit the closer

Technology