Home  >  Article  >  Backend Development  >  Learn more about the magic of Python

Learn more about the magic of Python

青灯夜游
青灯夜游Original
2019-11-26 17:58:332966browse

Learn more about the magic of Python

What is Python magic method

The magic method is as magical as its name, it can always provide you with something when you need it. ways to make your ideas come true. Magic methods refer to methods that are already included in Python and surrounded by double underscores. These methods are automatically called when performing specific operations. They are the crystallization of Python's object-oriented wisdom. It becomes particularly important for beginners to master the magic methods of Python.

Why use Python magic methods

Using Python's magic methods can make Python's degree of freedom higher, and magic methods can also be used when there is no need to rewrite It takes effect under the specified default conditions. When rewriting is needed, users can also rewrite some methods according to their own needs to meet their own expectations. And it is well known that Python is an object-oriented language. Python's basic magic method makes Python better at object-oriented.

##__imul__(self, other)Define the behavior of assignment multiplication: *=__itruediv__(self, other)Define the behavior of assignment true division: /=__ifloordiv__(self, other)Define the behavior of assignment integer division: //=__imod__(self, other)Define the behavior of assignment modulo algorithm: %=__ipow__(self, other[, modulo])Define the behavior of assignment exponentiation: **=__ilshift__ (self, other)Define the behavior of bitwise left shift of assignment: <<=__irshift__(self, other) Define the behavior of bitwise right shift of assignment: >>=__iand__(self, other)Define the behavior of bitwise AND operation of assignment: &= __ixor__(self, other)Define the behavior of assignment bitwise XOR operation: ^=##__ior__( self, other)__neg__(self)__pos__(self)__abs__(self)__invert__(self)__complex__(self)__int__(self)__float__(self) __round__(self[, n])__index__(self) 2. If you define a custom numeric type that may be used when slicing, you should define __index____enter__(self) 2. The return value of __enter__ is bound to the target of the with statement or the name after as__exit__(self, exc_type, exc_value, traceback)2. Generally used to handle exceptions, clean up work or do some daily work after the code block is executed

Magic method name

Description

Basic magic methods (more commonly used)

__new__(cls[, ...])1. The first method called when instantiating an object
2. Its parameters are directly passed to the __init__ method for processing
3.我们一般不会重写该方法
__init__(self[, ...])构造方法,初始化类的时候被调用
__del__(self)析构方法,当实例化对象被彻底销毁时被调用(实例化对象的所有指针都被销毁时被调用)
__call__(self[, args...])允许一个类的实例像函数一样被调用:x(a, b) 调用 x.__call__(a, b)
__len__(self)定义当被 len() 调用时的行为
__repr__(self)定义当被 repr() 调用时的行为
__str__(self)定义当被 str() 调用时的行为
__bytes__(self)定义当被 bytes() 调用时的行为
__hash__(self)定义当被 hash() 调用时的行为
__bool__(self)定义当被 bool() 调用时的行为,应该返回 True 或 False
__format__(self, format_spec)定义当被 format() 调用时的行为
 属性相关的方法
__getattr__(self, name)定义当用户试图获取一个不存在的属性时的行为
__getattribute__(self, name)定义当该类的属性被访问时的行为
__setattr__(self, name, value)定义当一个属性被设置时的行为
__delattr__(self, name)定义当一个属性被删除时的行为
__dir__(self)定义当 dir() 被调用时的行为
__get__(self, instance, owner)定义当描述符的值被取得时的行为
__set__(self, instance, value)定义当描述符的值被改变时的行为
__delete__(self, instance)定义当描述符的值被删除时的行为
 比较操作符
__lt__(self, other)定义小于号的行为:x < y 调用 x.__lt__(y)
__le__(self, other)定义小于等于号的行为:x <= y 调用 x.__le__(y)
__eq__(self, other)定义等于号的行为:x == y 调用 x.__eq__(y)
__ne__(self, other)定义不等号的行为:x != y 调用 x.__ne__(y)
__gt__(self, other)定义大于号的行为:x > y 调用 x.__gt__(y)
__ge__(self, other)定义大于等于号的行为:x >= y 调用 x.__ge__(y)
 算数运算符
__add__(self, other)定义加法的行为:+
__sub__(self, other)定义减法的行为:-
__mul__(self, other)定义乘法的行为:*
__truediv__(self, other)定义真除法的行为:/
__floordiv__(self, other)定义整数除法的行为://
__mod__(self, other)定义取模算法的行为:%
__divmod__(self, other)定义当被 divmod() 调用时的行为
__pow__(self, other[, modulo])定义当被 power() 调用或 ** 运算时的行为
__lshift__(self, other)定义按位左移位的行为:<<
__rshift__(self, other)定义按位右移位的行为:>>
__and__(self, other)定义按位与操作的行为:&
__xor__(self, other)定义按位异或操作的行为:^
__or__(self, other)定义按位或操作的行为:|
 反运算(类似于运算方法)
__radd__(self, other) 当被运算对象(左边的操作对象)不支持该运算时被调用
__rsub__(self, other) 当被运算对象(左边的操作对象)不支持该运算时被调用
__rmul__(self, other) 当被运算对象(左边的操作对象)不支持该运算时被调用
__rtruediv__(self, other) 当被运算对象(左边的操作对象)不支持该运算时被调用 
__rfloordiv__(self, other) 当被运算对象(左边的操作对象)不支持该运算时被调用
__rmod__(self, other) 当被运算对象(左边的操作对象)不支持该运算时被调用
__rdivmod__(self, other) 当被运算对象(左边的操作对象)不支持该运算时被调用
__rpow__(self, other) 当被运算对象(左边的操作对象)不支持该运算时被调用
__rlshift__(self, other) 当被运算对象(左边的操作对象)不支持该运算时被调用
__rrshift__(self, other)  当被运算对象(左边的操作对象)不支持该运算时被调用
__rxor__(self, other) 当被运算对象(左边的操作对象)不支持该运算时被调用
__ror__(self, other) 当被运算对象(左边的操作对象)不支持该运算时被调用
 增量赋值运算
__iadd__(self, other)Define the behavior of assignment addition: =
__isub__(self, other)Define the behavior of assignment subtraction: -=
Define the behavior of bitwise OR operation of assignment: |=
Unary operator
Define the behavior of the positive sign: x
Define the behavior of negative signs: -x
Define the behavior when called by abs()
Define the behavior of bitwise inversion: ~x
Type conversion
Define the behavior when called by complex() (needs to return the appropriate value)
Define the behavior when called by int() (need to return the appropriate value)
Define the behavior when called by float() (needs to return the appropriate value)
Definition Behavior when called by round() (needs to return the appropriate value)
1. When the object is used in a slice expression When, implement integer coercion 3. If __index__ is defined, __int__ also needs to be defined and returns the same value

Context management (with statement )
1. Define the initialization behavior when using the with statement
1. When defined What should the context manager do after a code block is executed or terminated
Container type (general Used to operate container classes)
__len__(self) Defines the behavior when called by len() (generally returns the container class Length)
__getitem__(self, key)Define the behavior of getting the specified element in the container, equivalent to self[key]
__setitem__(self, key, value)Define the behavior of setting the specified element in the container, equivalent to self[key] = value
__delitem__(self, key) defines the behavior of deleting the specified element in the container, which is equivalent to del self[key]
__iter__(self)defines when iterating the container Behavior of elements in
__reversed__(self)Defines the behavior when called by reversed()
__contains__ (self, item)Define the behavior when using the member test operator (in or not in)

Recommended learning: Python video Tutorial

The above is the detailed content of Learn more about the magic of Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn