Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the common magic methods used in python

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces the magic methods commonly used in python, which have a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand.

Magic method

Everything in python is an object because python is an object-oriented programming language. Python provides a large number of built-in methods for classes and objects, which are also called magic methods. These magic methods are always triggered automatically under certain conditions, just like magic.

_ _ init__ method

This method is used to initialize an empty object after receiving the empty object returned by the _ _ new__ method in the class when defining the class, and there is no return value.

Class Test (): def _ init__ (self, name): self.name = name def test (self): print (self.name) t = Test ('xu') T1 = Test (' python') _ _ new__ method

This method is the first method that is triggered when a class is called to instantiate an object, which is used to instantiate an empty object and return.

Class Test (): def _ new__ (cls,*args, * * kwargs): return object.__new__ (cls,*args, * * kwargs) def _ _ init__ (self, name): self.name = name__call__ method

If you want an object to become a callable object (you can call it with parentheses), you need to define the _ _ call__ method in the object's class, and the return value of the callable object is the return value of the _ _ call__ method.

Class Test (): def _ init__ (self): self.name = 'python' def _ call__ (self, * args, * * kwargs): # self is an object of class Test print (self) # print (self.name) t = Test () t () # python__str___ method

Triggers execution when an object is accessed and printed, and the method must have a return value of type string.

Class Test (): def _ init__ (self, name): self.name = name def _ str__ (self): return self.name t = Test ('xu') print (T1) # xu__del___ method

The _ _ del__ method is triggered automatically when the object is deleted. Because python's garbage collection mechanism automatically cleans up useless resources in the program, it is not necessary to define the _ _ del__ method if an object only occupies the resources of the application, but if it is designed to occupy system resources, such as open file objects, because it is related to the resources of the operating system. When python's garbage collection mechanism is not useful, you need to create a _ _ del__ method for the object, which is used to automatically trigger the recycling of operating system resources after the object is deleted.

Class Test: def _ _ init__ (self): self.x = open ('a. Txt _ del__ (self): print ('run') # initiates a system call Tell the operating system to reclaim the relevant system resources self.x.close () obj = T () del obj # obj.__del__ () _ _ enter__ & _ _ exit__ method

When using with context management, the _ _ enter__ method in the object is triggered and the return value of the _ _ enter__ method is assigned to the variable declared by as.

The _ _ exit__ method is triggered when the with statement ends normally. The three parameters of this method represent the exception type, outlier and traceability information, respectively. If there is an exception in the code block of the with statement, the code after the with statement will not be executed, but if the return value of the method is True, the exception will be cleared and the code after the with code block will be executed normally. The code is as follows:

Class Open: def _ _ init__ (self): self.name = 'open' def _ _ enter__ (self): print (the method that will be executed first when the' with statement is executed The return value will be assigned to the variable declared by as') return self.name def _ _ exit__ (self, exc_type, exc_val, exc_tb): print ('execute exit' when the code block in with finishes executing) print (exc_type,' if an exception indicates the exception type') print (exc_val, 'value of the exception') print (exc_tb) Return 123 # non-zero non-empty non-None is true with Open () as test: print (test) raise TypeError ('take a look at the error message') print ('will I be executed') # when the value returned by the _ _ exit__ method is true Will be executed, otherwise the item series of methods will not be executed

Item series methods include _ _ setitem__, _ _ getitem__, and delitem__ methods, which are triggered when square brackets are assigned / modified, selected and deleted, respectively. For example, you can customize a dictionary class and customize the methods for assigning, taking and deleting values from square brackets:

Class MyDict (dict): def _ setitem__ (self, key, value): print ('execute setitem', key, value) # execute setitem, x, 1 self.__dict__ [key] = value def _ _ getitem__ (self, item): print (' execute getitem', item) # execute getitem x print (self.__dict__ [item]) # 1 def _ delitem__ (self Key): print ('execute delitem', key) # execute delitem x self.__dict__.pop (key) d = MyDict () d [' x'] = 1print (d ['x']) del d ['x'] attr series methods

Attr series methods include: _ _ setattr__,__getattr__,__delattr__,__setattr__ triggers when adding / modifying attributes, _ delattr__ triggers when deleting attributes, and _ _ getattr__ is in use. Triggered when a property is called and the property does not exist. As shown in the following code

Class Test: def _ init__ (self): self.name = 'python' def _ setattr__ (self, key, value): print (' add / modify attribute setattr') self.__dict__ [key] = value # self.key = value # wireless recursion occurs because of the object. Property calls _ _ setattr__ method def _ _ delattr__ (self, item): print ('delete attribute delattr') self.__dict__.pop (item) def _ _ getattr__ (self, item): print (' call getattr' when attribute does not exist) t = Test () t.x = 'x'print (t.y) del t.x singleton mode

Singleton pattern is a kind of software design pattern, in order to ensure that no matter how many times a class invokes the resulting object, it points to the same memory address, that is, there is only one object.

There are many ways to implement the singleton pattern, and the general principle is to ensure that a class only instantiates an object, so the key point is how to determine whether the class has instantiated an object.

Here are several implementation methods for your reference:

The way the module is imported

The principle of this approach is that the module is only run once after it is imported, and the classes in the module are looked up directly from memory.

# cls_singleton.pyclass Foo (object): passinstance = Foo () # test.pyimport cls_singletonobj1 = cls_singleton.instanceobj2 = cls_singleton.instanceprint (obj1 is obj2) # True passes the _ _ new__ method

The principle is to determine whether the class has the strength, return it directly if you have it, and save it to _ instance if not.

Class Test: _ instance = None def _ _ init__ (self, name, age): self.name = name self.age = age def _ _ new__ (cls, * args * * kwargs): # if cls._instance: # return cls._instance # return directly # else: # cls._instance = super (). _ _ new__ (cls) # if there is no instance, new one and save # return cls._instance # this return is to init or not It doesn't matter if you instantiate it again. If not cls._instance: # this is a simplified way of writing. It is easier to withdraw the above notes to judge the way of thinking cls._instance = super (). _ new__ (cls) return cls._instancet1 = Test ('python', 18) T2 = Test (' python1', 18) print (T1 is T2) # True custom metaclass

The principle of this method is the procedure called by the class. When the class is defined, the _ _ init__, method under the metaclass is triggered when the _ _ call__ class under the metaclass is called (instantiating the object).

Class Mymeta (type): def _ _ init__ (cls, name, bases, dic): super (). _ _ init__ (name, bases, dic) cls._instance = None # put the data properties of the instance object of the record class into the metaclass and automatically define def _ _ call__ (cls, * args) * * kwargs): # this call will be triggered when the class is called (that is, when it is instantiated) if cls._instance: # determine whether the class has an instantiated object return cls._instance else: # when there is no instantiated object Control class hollowed out the object and initialized obj = cls.__new__ (cls, * args, * * kwargs) obj.__init__ (* args, * * kwargs) cls._instance = obj # Save object Next instantiation can be returned directly without having to recreate the object return objclass Test (metaclass=Mymeta): def _ init__ (self, name, age): self.name = name self.age = aget1 = Test ('python', 18) T2 = Test (' python1', 18) print (T1 is T2) # True Thank you for reading this article carefully I hope the article "what are the common magic methods of python" shared by the editor will be helpful to you. At the same time, I also hope that you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report