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.
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 assignment multiplication: *= | |
| Define the behavior of assignment true division: /= | |
| Define the behavior of assignment integer division: //= | |
| Define the behavior of assignment modulo algorithm: %= | |
| Define the behavior of assignment exponentiation: **= | |
| Define the behavior of bitwise left shift of assignment: <<= | |
| Define the behavior of bitwise right shift of assignment: >>= | |
| Define the behavior of bitwise AND operation of assignment: &= | |
| Define the behavior of assignment bitwise XOR operation: ^= | |
| 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 | 2. If you define a custom numeric type that may be used when slicing, you should define __index__
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 | 2. The return value of __enter__ is bound to the target of the with statement or the name after as|
| 1. When defined What should the context manager do after a code block is executed or terminated | 2. Generally used to handle exceptions, clean up work or do some daily work after the code block is executed|
| 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!
Hot AI Tools
Undresser.AI Undress
AI-powered app for creating realistic nude photos
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undress AI Tool
Undress images for free
Clothoff.io
AI clothes remover
AI Hentai Generator
Generate AI Hentai for free.
Hot Article
Hot Tools
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
1378
52
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.
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.
How to train PyTorch model on CentOS
Apr 14, 2025 pm 03:03 PM
Efficient training of PyTorch models on CentOS systems requires steps, and this article will provide detailed guides. 1. Environment preparation: Python and dependency installation: CentOS system usually preinstalls Python, but the version may be older. It is recommended to use yum or dnf to install Python 3 and upgrade pip: sudoyumupdatepython3 (or sudodnfupdatepython3), pip3install--upgradepip. CUDA and cuDNN (GPU acceleration): If you use NVIDIAGPU, you need to install CUDATool
How is the GPU support for PyTorch on CentOS
Apr 14, 2025 pm 06:48 PM
Enable PyTorch GPU acceleration on CentOS system requires the installation of CUDA, cuDNN and GPU versions of PyTorch. The following steps will guide you through the process: CUDA and cuDNN installation determine CUDA version compatibility: Use the nvidia-smi command to view the CUDA version supported by your NVIDIA graphics card. For example, your MX450 graphics card may support CUDA11.1 or higher. Download and install CUDAToolkit: Visit the official website of NVIDIACUDAToolkit and download and install the corresponding version according to the highest CUDA version supported by your graphics card. Install cuDNN library:
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 choose the PyTorch version under CentOS
Apr 14, 2025 pm 02:51 PM
When selecting a PyTorch version under CentOS, the following key factors need to be considered: 1. CUDA version compatibility GPU support: If you have NVIDIA GPU and want to utilize GPU acceleration, you need to choose PyTorch that supports the corresponding CUDA version. You can view the CUDA version supported by running the nvidia-smi command. CPU version: If you don't have a GPU or don't want to use a GPU, you can choose a CPU version of PyTorch. 2. Python version PyTorch
How to install nginx in centos
Apr 14, 2025 pm 08:06 PM
CentOS Installing Nginx requires following the following steps: Installing dependencies such as development tools, pcre-devel, and openssl-devel. Download the Nginx source code package, unzip it and compile and install it, and specify the installation path as /usr/local/nginx. Create Nginx users and user groups and set permissions. Modify the configuration file nginx.conf, and configure the listening port and domain name/IP address. Start the Nginx service. Common errors need to be paid attention to, such as dependency issues, port conflicts, and configuration file errors. Performance optimization needs to be adjusted according to the specific situation, such as turning on cache and adjusting the number of worker processes.
How to do data preprocessing with PyTorch on CentOS
Apr 14, 2025 pm 02:15 PM
Efficiently process PyTorch data on CentOS system, the following steps are required: Dependency installation: First update the system and install Python3 and pip: sudoyumupdate-ysudoyuminstallpython3-ysudoyuminstallpython3-pip-y Then, download and install CUDAToolkit and cuDNN from the NVIDIA official website according to your CentOS version and GPU model. Virtual environment configuration (recommended): Use conda to create and activate a new virtual environment, for example: condacreate-n


