We’re going to use a class that takes you through the ways in which magic methods in Python code can be misunderstood,

You are welcome to comment and correct my mistakes,

Some magic methods are not described in the documentation or PEP,

We also welcome big guy comment supplement

We will update your additional paragraphs to the blog post as soon as possible with your gold ID




#! /usr/bin/python3
# _*_ Coding: UTF-8 _*_
from __future__ import division

import collections
import copy
import math
import operator
import pickle
import sys
import asyncio
from typing import可迭代class MedusaSorcerer:
    instance = 'medusa'

    def __abs__(self) :
        """ >>> abs(MedusaSorcerer()) returns the absolute value of a number """
        return '__abs__'

    def __add__(self, other) :
        """ >>> MedusaSorcerer() + 123
        return '__add__'

    async def __aenter__(self) :
        An asynchronous context manager is a type of context manager that can suspend execution in its __aenter__ and __aexit__ methods. It is semantically similar to __enter__ except that it must return a awaitable object. https://docs.python.org/zh-cn/3/reference/datamodel.html?highlight=__aenter__#object.__aenter__ """
        await asyncio.sleep(123)

    async def __aexit__(self, exc_type, exc_val, exc_tb) :
        An asynchronous context manager is a type of context manager that can suspend execution in its __aenter__ and __aexit__ methods. It is semantically similar to __exit__ except that it must return a awaitable object. https://docs.python.org/zh-cn/3/reference/datamodel.html?highlight=__aenter__#object.__aexit__ """
        await asyncio.sleep(123)

    def __aiter__(self) :
        An asynchronous iterator may call asynchronous code in its __anext__ method to return an asynchronous iterator object. https://docs.python.org/zh-cn/3/reference/datamodel.html?highlight=__aiter__#object.__aiter__ """
        return self

    def __and__(self, other) :
        """ >>> MedusaSorcerer() & 123
        return '__and__ True'

    def __anext__(self) :
        """ """ """ """ """ """ """ """ """ """ """ """ "" https://docs.python.org/zh-cn/3/reference/datamodel.html?highlight=__aiter__#object.__anext__ """
        pass

    def __await__(self) :
        "" "returns an iterator The official Chinese documents: https://docs.python.org/zh-cn/3/reference/datamodel.html?highlight=__aiter__#object.__await__ "" "
        pass

    def __call__(self, *args, **kwargs) :
        """ >>> MedusaSorcerer()() call object (callable): but any object to which a pair of parentheses () can be applied is called a callable object. If a class implements __call__, then the instance object will also be a callable object. """
        self.params = '__call__'

    def __init__(self, **kwargs) :
        """ >>> MedusaSorcerer(element='__element__') method of initializing instance attributes after constructing an instance object """
        self.params = 'params'
        self.element = kwargs.get('element')

    def __bool__(self) :
        """ >>> if MedusaSorcerer(): print('True') schedule this method when Boolean comparison """
        return True

    def __bytes__(self) :
        """ >>> bytes(MedusaSorcerer()) returns the method of byte array scheduling """
        return bytes('123', encoding='UTF-8')

    def __ceil__(self) :
        """ >>> Schedule this method when math.ceil(MedusaSorcerer()) returns the smallest integer """
        return '__ceil__'

    def __class_getitem__(cls, item) :
        Returns a specialized object representing a generic class of the type specified by the key argument. You may also need to consult PEP484 and PEP560: https://docs.python.org/zh-cn/3/reference/datamodel.html?highlight=__class_getitem__#object.__class_getitem__ PEP560 case and instructions: https://www.python.org/dev/peps/pep-0560/#class-getitem "" "
        pass

    def __cmp__(self, other) :
        >>> sorted(MedusaSorcerer(), MedusaSorcerer()); Return -1 if the params property of the passed object is larger than the params property of the instance object: +1 if the params property of the passed object is smaller than the params property of the instance object: +1 Return 0 "" "
        if self.params < other.params:
            return -1
        elif self.params > other.params:
            return 1
        return 0

    def __coerce__(self, other) :
        """ >>> COERce (MedusaSorcerer(), MedusaSorcerer()) implemented mixed-mode operations that are obsolete in Python3 """
        pass

    def __complex__(self) :
        """ >>> schedule this method for complex(MedusaSorcerer())
        return complex(123)

    def __contains__(self, item) :
        """ >>> item not in MedusaSorcerer() >>> item in MedusaSorcerer()
        return True if item == '123' else False

    def __copy__(self) :
        """
        >>> copy.copy(MedusaSorcerer())
        返回浅拷贝对象
        """
        return 123

    def __deepcopy__(self, memodict={}) :
        """ >>> copy. Deepcopy (MedusaSorcerer()) returns a deepcopy object """
        return self

    def __del__(self) :
        """ >>> medusa = MedusaSorcerer() >>> behavior function of del Medusa object during garbage collection """
        print('__del__')

    def __delattr__(self, item) :
        """ >>> del self.params implementation will schedule this method when deleting instance properties """
        self.__dict__.pop(item)

    def __delete__(self, instance) :
        """ >>> class Test: medusa = MedusaSorcerer() >>> del Test(). Call this method to delete attributes of an instance of the owner class specified by instance. Call this method when the instance owner deletes it.
        print('__delete__')

    def __delitem__(self, key) :
        """ >>> del MedusaSorcerer()['params'] will schedule this method when deleting with key-value pairs """
        self.__dict__.pop(key)

    def __delslice__(self, i, j) :
        """ __getSlice__, __setslice__, and __delslice__ : The three operations used for sharding are deprecated in Python3. """
        pass

    def __dir__(self) -> Iterable[str] :
        """ >>> dir(MedusaSorcerer()) returns all instance properties and methods
        return super().__dir__()

    def __divmod__(self, other) :
        """ >>> Divmod (MedusaSorcerer(), 123) returns an array of tuples
        return 123.123

    def __enter__(self) :
        """ >>> With MedusaSorcerer(): Pass needs to implement this method when scheduling with statement blocks """
        self.enter = '__enter__'

    def __eq__(self, other) :
        """ >>> MedusaSorcerer() == 123
        return True

    def __exit__(self, exc_type, exc_val, exc_tb) :
        """ >>> with MedusaSorcerer(): When the pass exits the with block the method is scheduled to exit the runtime context associated with the object each parameter describes the exception that causes the context to exit if the context exits without exception, All three arguments will be None. If an exception is provided and you want the method to mask it (that is, avoid it being propagated) then true should be returned. Otherwise, the exception will be handled as normal when exiting the method. """
        self.enter = '__exit__'

    def __float__(self) :
        """ >>> float(MedusaSorcerer()) returning a float will schedule the method """
        return float(123)

    def __floor__(self) :
        """ >>> Schedule this method when math.floor(MedusaSorcerer()) returns the maximum integer """
        return '__floor__'

    def __floordiv__(self, other) :
        """ >>> MedusaSorcerer() // 123 will schedule the method when the division operation is performed """
        return 123.0

    def __format__(self, format_spec) :
        """ >>> format(MedusaSorcerer(), 'self.params = %params%') format the string as a format string
        return format_spec.replace('%params%', self.params)

    def __fspath__(self) :
        """ PEP 519 Returns the file system of the current object means that this method should only return a STR string or a bytes string, with STR string preferred https://docs.python.org/zh-cn/3/library/os.html?highlight=__fspath__#os.PathLike.__fspath__ https://www.python.org/dev/peps/pep-0519/#protocol https://www.python.org/dev/peps/pep-0519/#have-fspath-only-return-strings """
        pass

    def __ge__(self, other) :
        """ >>> MedusaSorcerer() >= 123
        return True

    def __get__(self, instance, owner) :
        """ >>> class Test: medusa = MedusaSorcerer() >>> print(Test().medusa) The optional owner argument is the owner class and instance is the instance that is used to access the property. If the property is accessed through the owner, return None. Call the method """ "when the instance owner queries it.
        return '__get__'

    def __getattr__(self, item) :
        """ >>> MedusaSorcerer().params_2 = 123 A reference to an instance attribute that does not exist will be scheduled. __getAttr__ will not be called when __getAttr__ is present, unless an invocation is made or an AttributeError is raised. """
        return f'object has no attribute "{item}"'

    def __getattribute__(self, item) :
        """ >>> MedusaSorcerer(). Params refers to the presence of instance attributes and schedules that __getAttr__ will not be called when __getAttr__ is present, unless an invocation is made or an AttributeError is raised. """
        return super().__getattribute__(item)

    def __getinitargs__(self) :
        """ >>> pickle.loads(pickle.dumps(MedusaSorcerer()))) in the old class (the new class is all the default in Python 3.x, the classic class is removed), Then you need to define the method and return the tuple of arguments required for __init__. """
        return '__getinitargs__'.def __getitem__(self, item) :
        """ >>> MedusaSorcerer()['params']
        return self.__dict__.get(item)

    def __getnewargs__(self) :
        """ >>> pickle.loads(pickle.dumps(MedusaSorcerer())) This method should return a tuple of arguments. Before Python3.6, the second and third guild would call __getNewargs__, Pickle does not call any of the following functions directly: __getnewargs_ex__ __getnewargs__ __ getState__ In fact, these functions are part of the replication protocol that implements a special interface called __reduce__ which provides a unified interface, Although this protocol is powerful, implementing the __reduce__ interface directly in a class is prone to errors. Therefore, you should design your classes using the advanced interface whenever possible. For example __getnewargs_ex__, __getState__, and __setState__ """
        return '__getnewargs__'.def __getstate__(self) :
        """ >>> pickle.loads(pickle.dumps(MedusaSorcerer())) Gets the state of an object before pickling. Pickle does not call the following functions directly: __getnewargs_ex__ __getnewargs__ __ getState__ In fact, these functions are part of the replication protocol that implements a special interface called __reduce__ which provides a unified interface, Although this protocol is powerful, implementing the __reduce__ interface directly in a class is prone to errors. Therefore, you should design your classes using the advanced interface whenever possible. For example __getnewargs_ex__, __getState__, and __setState__ """
        return self.__dict__

    def __gt__(self, other) :
        """ >>> MedusaSorcerer() > 123
        return False

    def __hash__(self) :
        """ >>> Hash (MedusaSorcerer()) returns a custom hash value """
        return -123

    def __hex__(self) :
        """ __oct__, __hex__: use __index__ in OCT () and hex() instead. Python3 has discarded official Chinese documents: https://docs.python.org/zh-cn/3/whatsnew/3.0.html?highlight=__hex__#operators-and-special-methods "" "
        pass

    def __iadd__(self, other) :
        """ >>> medusa = MedusaSorcerer() >>> medusa += 123
        return self.params + f'{str(other)}(__iadd__)'

    def __iand__(self, other) :
        """ >>> medusa = MedusaSorcerer() >>> medusa &= 123
        return '__iand__ True'

    def __idiv__(self, other) :
        """ >>> medusa = MedusaSorcerer() >>> medusa /= 123 Implementations of in-place division Python3 no longer uses this method, migrate to __itruediv__ """
        return '__idiv__'

    def __ifloordiv__(self, other) :
        """ >>> medusa = MedusaSorcerer() >>> medusa //= 123
        return '__ifloordiv__'

    def __ilshift__(self, other) :
        """ >>> medusa = MedusaSorcerer() >>> medusa <<= 123
        return 123 << other

    def __imatmul__(self, other) :
        "" "refer to PEP465: https://www.python.org/dev/peps/pep-0465/#specification, the official Chinese documents (no documentation) : https://docs.python.org/zh-cn/3/reference/datamodel.html?highlight=__imatmul__#object.__imatmul__ """
        pass

    def __imod__(self, other) :
        """ >>> medusa = MedusaSorcerer() >>> medusa %= 123
        return '__imatmul__'

    def __imul__(self, other) :
        """ >>> medusa = MedusaSorcerer() >>> medusa *= 123
        return '__imul__'

    def __index__(self) :
        """ >>> bin(MedusaSorcerer()) >>> hex(MedusaSorcerer()) >>> oct(MedusaSorcerer()) >>> operator.index(MedusaSorcerer()) This method is called to implement operator.index() and in cases where Python needs to convert a numeric object to an integer object lossless, such as slicer or the built-in bin(), hex(), and oct() functions. This method indicates that the numeric object is of an integer type and must return an integer. """
        return 123

    def __init_subclass__(cls, **kwargs) :
        """ >>> class Test(MedusaSorcerer, params='class Test'): ... >>> print(test.params) When a class inherits from another class, that class's __init_subclass__ is called so that you can write classes that change the behavior of subclasses __init_subclass__ only applies to subclasses derived from the class that defines the method """
        cls.params = '__init_subclass__' if not kwargs.get('params') else kwargs.get('params')
        super().__init_subclass__()

    def __instancecheck__(self, instance) :
        """ >>> class BaseTypeClass(type): >>> def __new__(cls, name, bases, namespace, **kwd): return type.__new__(cls, name, bases, namespace) >>> def __instancecheck__(self, other): return False >>> class A(metaclass=BaseTypeClass): ... >>> print(isinstance(A(), A)) controls whether an object is an instance of that object. The isinstance function does A quick check to see if the provided instance is of the same type as the class. And the __instancecheck__ method is not called. This is an optimization used to avoid unnecessary complex calls to __instancecheck__. """
        pass

    def __int__(self) :
        """ >>> int(MedusaSorcerer()) converted to numeric scheduling method """
        return 123

    def __invert__(self) :
        """ >>> ~MedusaSorcerer() return value scheduling method for unary operation """
        return ~123

    def __ior__(self, other) :
        "" "> > > medusa = MedusaSorcerer () > > > medusa | = 123 the realizing methods of in situ bitwise or operation "" "
        return '__ior__'

    def __ipow__(self, other) :
        """ >>> medusa = MedusaSorcerer() >>> medusa **= 123
        return '__ipow__'

    def __irshift__(self, other) :
        >>> medusa = MedusaSorcerer() >>> medusa >>= 123
        return '__irshift__'

    def __isub__(self, other) :
        """ >>> medusa = MedusaSorcerer() >>> medusa -= 123
        return '__isub__'

    def __iter__(self) :
        """ >>> medusa = iter(MedusaSorcerer()) >>> next(medusa) create an iterable that needs to implement the __next__ method.
        self.integer = 0
        return self

    def __itruediv__(self, other) :
        """ >>> medusa = MedusaSorcerer() >>> medusa /= 123
        return '__itruediv__'

    def __ixor__(self, other) :
        """ >>> medusa = MedusaSorcerer() >>> medusa ^= 123
        return '__ixor__'

    def __le__(self, other) :
        """ >>> MedusaSorcerer() <= 123 Defines the less than or equal operator behavior """
        return '__le__'

    def __len__(self) :
        """ >>> len(MedusaSorcerer()) returns the length of the container """
        return len(self.params)

    def __long__(self) :
        """ >>> long(MedusaSorcerer) Long conversion required by Python2 """
        return '__long__'

    def __lshift__(self, other) :
        """ >>> MedusaSorcerer() << 123
        return '__lshift__'

    def __lt__(self, other) :
        """ >>> MedusaSorcerer() < 123 Defines less than operator behavior """
        return '__lt__'

    def __matmul__(self, other) :
        "" "refer to PEP465: https://www.python.org/dev/peps/pep-0465/#specification, the official Chinese documents (no documentation) : https://docs.python.org/zh-cn/3/reference/datamodel.html?highlight=__imatmul__#object.__matmul__ """
        pass

    def __missing__(self, key) :
        """ >>> class Dict(dict): >>> def __missing__(self, key): return f'__missing__({key})' >>> medusa = Dict({'1': 1}) >>> print(medusa['123'])
        pass

    def __mod__(self, other) :
        """ >>> MedusaSorcerer() % 123
        return '__mod__'

    def __mro_entries__(self, bases) :
        If a base class appears in a class definition that is not an instance of type, search for it using the __mro_entries__ method. When found, it will be called with the original base tuple. This method must return the tuple of the class in place of the base class being used. In this case, the original base class will be ignored. Please refer to the official Chinese document of PEP560: https://docs.python.org/zh-cn/3/reference/datamodel.html?highlight=__imatmul__#resolving-mro-entries https://www.python.org/dev/peps/pep-0560/#mro-entries """
        pass

    def __mul__(self, other) :
        """ >>> MedusaSorcerer() * 123
        return '__mul__'

    def __ne__(self, other) :
        """ >>> MedusaSorcerer() ! = 123 Define unequal judgment behavior """
        return '__ne__'

    def __neg__(self) :
        """ >>> -medusasorcerer () implements the method of taking negative behavior """
        return '__neg__'

    def __new__(cls, *args, **kwargs) :
        """ >>> This method will be scheduled first when the MedusaSorcerer() class object is instantiated.
        if '__getnewargs__' in args: return 123
        return super().__new__(cls)

    def __next__(self) :
        """ >>> medusa = iter(MedusaSorcerer()) >>> next(medusa)
        self.integer += 1
        return self.integer

    def __oct__(self) :
        """ >>> Oct (MedusaSorcerer()) implements octal conversion, which is overwritten by __index__ """
        return '__oct__'

    def __or__(self, other) :
        "" "> > > MedusaSorcerer () | 132 realize the bitwise or operator ", ""
        return '__or__'

    def __pos__(self) :
        """ >>> +MedusaSorcerer() implements positive behavior """
        return '__pos__'

    def __pow__(self, power, modulo=None) :
        """ >>> MedusaSorcerer() ** 123
        return '__pow__'

    @classmethod
    def __prepare__(metacls, name, bases) :
        """ >>> MedusaSorcerer() __prepare__ is only useful in metaclasses, and must be declared as a class method. The main function of the method is to list the order in which the class attributes are defined. The first argument is the metaclasses, followed by the tuple of the base class and the name of the class to be built. When building a new class, the interpreter first calls the __prepare__ method, Create the mapping using the attributes in the class body and then pass the mapping returned by the __prepare__ method as the last argument to the __new__ method and then to the __init__ method where we pass an empty OrderedDict instance object """ "
        return collections.OrderedDict()

    def __radd__(self, other) :
        """ >>> 123 + MedusaSorcerer
        return '__radd__'

    def __rand__(self, other) :
        """ >>> 123 & MedusaSorcerer() implements reflection bitwise and operator """
        return '__rand__'

    def __rdiv__(self, other) :
        """ >>> 123 / MedusaSorcerer() implement reflection division Python3 invalid """
        return '__rdiv__'

    def __rdivmod__(self, other) :
        """ >>> divmod(123, MedusaSorcerer()) returns a reflected tuple array """
        return '__rdivmod__'

    def __reduce__(self) :
        """ >>> pickle.dumps(MedusaSorcerer()) When defining extension types that are implemented using Python's C API if you want to pickle them, You must tell Python how to pickle them. After __reduce__ is defined, the object is called when it is pickled. It either returns a string representing the global name, which Python will look for and pickle, or returns a tuple containing 2 to 5 elements: (optional) An iterator that generates pickled list elements (optional) an iterator that generates pickled dictionary elements (optional) """
        return super().__reduce__()

    def __reduce_ex__(self, protocol) :
        """ >>> pickle.dumps(MedusaSorcerer()) __reduce_ex__ exists for compatibility. If it is defined, __reduce_ex__ is called instead of __reduce__ when pickling. """
        return super().__reduce_ex__(protocol)

    def __repr__(self) :
        """ >>> repr(MedusaSorcerer()) returns the data that the object converts into a form that can be read by the interpreter. """
        return '__repr__'

    def __reversed__(self) :
        """ >>> return a reversed iterator (MedusaSorcerer()) """
        return '__reversed__'

    def __rfloordiv__(self, other) :
        """ >>> 123 // MedusaSorcerer()
        return '__rfloordiv__'

    def __rlshift__(self, other) :
        """ >>> 123 << MedusaSorcerer()
        return '__rlshift__'

    def __rmatmul__(self, other) :
        "" "PEP465 (no documentation) : https://www.python.org/dev/peps/pep-0465/#specification, the official Chinese documents (no documentation) : https://docs.python.org/zh-cn/3/reference/datamodel.html?highlight=__rmatmul__#object.__rmatmul__ """
        pass

    def __rmod__(self, other) :
        """ >>> 123 % MedusaSorcerer() implements the reflectometer operator """
        return '__rmod__'

    def __rmul__(self, other) :
        """ >>> 123 * MedusaSorcerer()
        return '__rmul__'

    def __ror__(self, other) :
        """
        >>> 123 | MedusaSorcerer()
        实现反射按位或运算符
        """
        return '__ror__'

    def __round__(self, n=None) :
        """ >>> round(MedusaSorcerer()) implements the round value of n floating point """
        return '__round__'

    def __rpow__(self, other) :
        """ >>> 123 ** MedusaSorcerer() reflect power value operator """
        return '__rpow__'

    def __rrshift__(self, other) :
        """ >>> 123 >> MedusaSorcerer()
        return '__rrshift__'

    def __rshift__(self, other) :
        """ >>> MedusaSorcerer() >> 123
        return '__rshift__'

    def __rsub__(self, other) :
        """ >>> 123-medusasorcerer ()
        return '__rsub__'

    def __rtruediv__(self, other) :
        """ >>> 123 / MedusaSorcerer() implement _true_reflection division Python2 This function only works if you use from __future__ import division.
        return '__rtruediv__'

    def __rxor__(self, other) :
        """ >>> 123 ^ MedusaSorcerer() implements the reflection bitwise Xor operator """
        return '__rxor__'

    def __set__(self, instance, value) :
        """ >>> class Test: Medusa = MedusaSorcerer() >>> Test().medusa = 1 A class is called when its owner changes its value. To be a descriptor, __get__, __set__, At least one method in __delete__ """
        instance.params = value

    def __set_name__(self, owner, name) :
        """ is called when the owner class is created, and the descriptor is assigned to name. https://docs.python.org/zh-cn/3/reference/datamodel.html?highlight=__set_name__#object.__set_name__ https://www.python.org/dev/peps/pep-0487/#proposal """
        pass

    def __setattr__(self, key, value) :
        """ >>> self.params = 123 This method will be scheduled when the instance object sets instance properties """
        self.__dict__[key] = value

    def __setitem__(self, key, value) :
        "" "> > > MedusaSorcerer () [' key] = 123, using the key way to increase element value "" "
        self.__dict__[key] = value

    def __setslice__(self, i, j, sequence) :
        """ __getSlice__, __setslice__, and __delslice__ : The three operations used for sharding are deprecated in Python3. """
        pass

    def __setstate__(self, state) :
        """ >>> pickle.loads(pickle.dumps(MedusaSorcerer())) When an object is being depickled, if __setState__ is defined, The state of the object is passed to the magic method instead of directly applying to the object's __dict__ property. The magic method and __getState__ are interdependent. When both methods are defined, You can use any method to save any state of an object during pickling and restore the state of the object after unpickling. """
        pass

    def __sizeof__(self) :
        """ >>> sys.getSizeof (MedusaSorcerer()) returns the sizeof the object """
        return 123

    def __str__(self) :
        """ >>> STR (MedusaSorcerer()) >>> print(MedusaSorcerer())
        return '__str__'

    def __sub__(self, other) :
        """ >>> MedusaSorcerer() -123
        return '__sub__'

    def __subclasscheck__(self, subclass) :
        >>> isSubClass (MedusaSorcerer(), MedusaSorcerer) Class) will determine if subclass is a subclass of that class and the return will be consistent with __instancecheck__, ignoring the method """
        pass

    def __truediv__(self, other) :
        """ >>> MedusaSorcerer() // 123 implements Python2 only if you declare from __future__ import division """
        return '__truediv__'

    def __trunc__(self) :
        """ >>> math.trunc(MedusaSorcerer())
        return '__trunc__'

    def __unicode__(self) :
        """ >>> Unicode (MedusaSorcerer()) Implements Unicode transcoding in Python2 """
        pass

    def __xor__(self, other) :
        """ >>> MedusaSorcerer() ^ 123 implements bitwise XOR operator """
        return '__xor__'

Copy the code