Home  >  Article  >  Backend Development  >  Let’s talk about common magic methods in Python

Let’s talk about common magic methods in Python

王林
王林forward
2023-05-15 22:34:04898browse

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