search
HomeBackend DevelopmentPython TutorialLet's talk about common magic methods in Python

Let's talk about common magic methods in Python

May 15, 2023 pm 10:34 PM
pythoncodemagic 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']

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"

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>)

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]

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
This article is reproduced at:51CTO.COM. If there is any infringement, please contact admin@php.cn delete
Learning Python: Is 2 Hours of Daily Study Sufficient?Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python for Web Development: Key ApplicationsPython for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python vs. C  : Exploring Performance and EfficiencyPython vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Python in Action: Real-World ExamplesPython in Action: Real-World ExamplesApr 18, 2025 am 12:18 AM

Python's real-world applications include data analytics, web development, artificial intelligence and automation. 1) In data analysis, Python uses Pandas and Matplotlib to process and visualize data. 2) In web development, Django and Flask frameworks simplify the creation of web applications. 3) In the field of artificial intelligence, TensorFlow and PyTorch are used to build and train models. 4) In terms of automation, Python scripts can be used for tasks such as copying files.

Python's Main Uses: A Comprehensive OverviewPython's Main Uses: A Comprehensive OverviewApr 18, 2025 am 12:18 AM

Python is widely used in data science, web development and automation scripting fields. 1) In data science, Python simplifies data processing and analysis through libraries such as NumPy and Pandas. 2) In web development, the Django and Flask frameworks enable developers to quickly build applications. 3) In automated scripts, Python's simplicity and standard library make it ideal.

The Main Purpose of Python: Flexibility and Ease of UseThe Main Purpose of Python: Flexibility and Ease of UseApr 17, 2025 am 12:14 AM

Python's flexibility is reflected in multi-paradigm support and dynamic type systems, while ease of use comes from a simple syntax and rich standard library. 1. Flexibility: Supports object-oriented, functional and procedural programming, and dynamic type systems improve development efficiency. 2. Ease of use: The grammar is close to natural language, the standard library covers a wide range of functions, and simplifies the development process.

Python: The Power of Versatile ProgrammingPython: The Power of Versatile ProgrammingApr 17, 2025 am 12:09 AM

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

Learning Python in 2 Hours a Day: A Practical GuideLearning Python in 2 Hours a Day: A Practical GuideApr 17, 2025 am 12:05 AM

Yes, learn Python in two hours a day. 1. Develop a reasonable study plan, 2. Select the right learning resources, 3. Consolidate the knowledge learned through practice. These steps can help you master Python in a short time.

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

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

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.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment