Home Backend Development Python Tutorial Learn more about the magic of Python

Learn more about the magic of Python

Nov 26, 2019 pm 05:58 PM
python magic method

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Detailed explanation of docker principle Detailed explanation of docker principle Apr 14, 2025 pm 11:57 PM

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

See all articles