Table of Contents
What is a magic method?
Commonly used magic methods
1. Construction and initialization
2. Control attribute access. This type of magic
3. Container class operations
Summary
Home Backend Development Python Tutorial Let's talk about common magic methods in Python

Let's talk about common magic methods in Python

May 15, 2023 pm 10:34 PM
python code magic method

What is a magic method?

Magic Methods are built-in functions in Python, generally starting and ending with double underscores, such as __init__, __del__, etc. They are called magic methods because these methods are automatically called when performing specific operations.

In Python, you can use the dir() method to view all methods and attributes of an object. The magic methods starting and ending with double underscores are the object's magic methods. Take the string object as an example:

>>> dir("hello")
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__',
'__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mo
d__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__',
'__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center',
'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'isl
ower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', '
rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate'
, 'upper', 'zfill']
Copy after login

You can see that the string object has the __add__ method, so you can directly use the " " operation on the string object in Python. When Python recognizes the " " operation, The __add__ method of the object will be called. When necessary, we can override the __add__ method in our own class to achieve the desired effect.

class A(object):
def __init__(self, str):
self.str = str


• def __add__(self, other):
• print ('overwrite add method')
• return self.str + "---" + other.str


>>>a1 = A("hello")
>>>a2 = A("world")
>>>print (a1 + a2)
>>>overwrite add method
>>>"hello---world"
Copy after login

We have rewritten the __add__ method. When Python recognizes the " " operation, it will automatically call the rewritten __add__ method. As you can see, magic methods will be automatically executed after certain events of the class or object are triggered. If you want to customize a class with special functions according to your own program, you need to rewrite these methods. Using magic methods, we can add special functions to classes very easily.

Commonly used magic methods

1. Construction and initialization

__new__, __init__ These two magic methods are often used to initialize classes. When we created a1 = A("hello") above, the first thing we called was __new__; initializing a class is divided into two steps:

  • a. Call the new method of the class and return the class Instance object
  • b. Call the init method of this class to initialize the instance object

__new__(cls, *args, **kwargs) requires at least one cls parameter, representing The class passed in. The last two parameters are passed to __init__. In __new__, you can decide whether to continue calling the __init__ method. Only when __new__ returns an instance of the current class cls, will __init__ be called. Combined with the characteristics of the __new__ method, we can implement Python's singleton mode by overriding the __new__ method:

class Singleton(object):
def __init__(self):
print("__init__")

• def __new__(cls, *args, **kwargs):
• print("__new__")
• if not hasattr(Singleton, "_instance"):
• print("创建新实例")
• Singleton._instance = object.__new__(cls)
• return Singleton._instance

>>> obj1 = Singleton()
>>> __new__
>>> 创建新实例
>>> __init__
>>> obj2 = Singleton()
>>> __new__
>>> __init__
>>> print(obj1, obj2)
>>> (<__main__.Singleton object at 0x0000000003599748>, <__main__.Singleton object at 0x0000000003599748>)
Copy after login

You can see that although two objects are created, two The addresses of the objects are the same.

2. Control attribute access. This type of magic

method mainly works when accessing, defining, and modifying the properties of an object. The main ones are:

  • __getattr__(self, name): Define the behavior when the user tries to get an attribute.
  • __getattribute__(self, name): Define the behavior when an attribute of this class is accessed (first call this method to see if the attribute exists, if not, then call getattr).
  • __setattr__(self, name, value): Defines the behavior when an attribute is set.

The magic method self.__setattr__(name,values) is called when initializing attributes such as self.a=a or modifying instance attributes such as ins.a=1; when the instance accesses a Attributes such as ins.a essentially call the magic method a.__getattr__(name)

3. Container class operations

There are some methods that allow us to define our own containers, just like Python’s built-in List, Tuple, Dict, etc.; containers are divided into mutable containers and immutable containers.

If you customize an immutable container, you can only define __len__ and __getitem__; to define a variable container, in addition to all the magic methods of the immutable container, you also need to define __setitem__ and __delitem__; if Containers are iterable. You also need to define __iter__.

  • __len__(self): Returns the length of the container
  • __getitem__(self,key): When you need to execute self[key] to call the object in the container, the call is This method __setitem__(self,key,value): When self[key] = value needs to be executed, this method is called
  • __iter__(self): When the container can execute for x in container:, or use iter(container), you need to define this method

The following is an example to implement a container that has the general functions of List, while adding some other functions such as accessing the first element, the last elements, record the number of times each element is accessed, etc.

class SpecialList(object):
def __init__(self, values=None):
self._index = 0
if values is None:
self.values = []
else:
self.values = values
self.count = {}.fromkeys(range(len(self.values)), 0)

def __len__(self):# 通过len(obj)访问容器长度
return len(self.values)

def __getitem__(self, key):# 通过obj[key]访问容器内的对象
self.count[key] += 1
return self.values[key]

def __setitem__(self, key, value):# 通过obj[key]=value去修改容器内的对象
self.values[key] = value

def __iter__(self):# 通过for 循环来遍历容器
return iter(self.values)

def __next__(self):
# 迭代的具体细节
# 如果__iter__返回时self 则必须实现此方法
if self._index >= len(self.values):
raise StopIteration()
value = self.values[self._index]
self._index += 1
return value

def append(self, value):
self.values.append(value)

def head(self):
# 获取第一个元素
return self.values[0]

def last(self):
# 获取最后一个元素
return self.values[-1]
Copy after login

The usage scenario of this method is mainly used when you need to define a container class data structure that meets your needs. For example, you can try to customize data structures such as tree structures and linked lists. (all available in collections), or some container types that need to be customized in the project.

Summary

Magic methods can simplify the code in Python code and improve the readability of the code. You can see many applications of magic methods in common Python third-party libraries. Therefore, this current article is just an introduction. Real use requires continuous deepening of understanding and appropriate application in the excellent open source source code and one's own engineering practice.

The above is the detailed content of Let's talk about common magic methods in 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

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.

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.

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.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang vs. Python: Concurrency and Multithreading Golang vs. Python: Concurrency and Multithreading Apr 17, 2025 am 12:20 AM

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

Can vscode run ipynb Can vscode run ipynb Apr 15, 2025 pm 07:30 PM

The key to running Jupyter Notebook in VS Code is to ensure that the Python environment is properly configured, understand that the code execution order is consistent with the cell order, and be aware of large files or external libraries that may affect performance. The code completion and debugging functions provided by VS Code can greatly improve coding efficiency and reduce errors.

See all articles