search
HomeBackend DevelopmentPython TutorialLearn more about the magic of Python
Learn more about the magic of PythonNov 26, 2019 pm 05:58 PM
pythonmagic 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
__le__(self, other) 定义小于等于号的行为:x
__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
详细讲解Python之Seaborn(数据可视化)详细讲解Python之Seaborn(数据可视化)Apr 21, 2022 pm 06:08 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

详细了解Python进程池与进程锁详细了解Python进程池与进程锁May 10, 2022 pm 06:11 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

Python自动化实践之筛选简历Python自动化实践之筛选简历Jun 07, 2022 pm 06:59 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

归纳总结Python标准库归纳总结Python标准库May 03, 2022 am 09:00 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于标准库总结的相关问题,下面一起来看一下,希望对大家有帮助。

Python数据类型详解之字符串、数字Python数据类型详解之字符串、数字Apr 27, 2022 pm 07:27 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

分享10款高效的VSCode插件,总有一款能够惊艳到你!!分享10款高效的VSCode插件,总有一款能够惊艳到你!!Mar 09, 2021 am 10:15 AM

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

详细介绍python的numpy模块详细介绍python的numpy模块May 19, 2022 am 11:43 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。

python中文是什么意思python中文是什么意思Jun 24, 2019 pm 02:22 PM

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。

See all articles

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 Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.