Python magic method-MagicMethod
Shao
In Python, all methods wrapped with underscores (_) are collectively referred to as "Magic Method". for example, the class initialization Method _ init __, all the magic methods in Python are described in the official documentation, but the official descriptions are chaotic and loosely organized. It is hard to find an example.
Construction and initialization
Every Pythoner knows the most basic magic method, _ init __. With this method, we can define the initial operation of an object. However, when calling x = SomeClass (), _ init _ is not the first method to be called. In fact, there is also a method called _ new _, which together constitute a "constructor ".
_ New _ is used to create a class and return the instance of this class. _ init _ only initializes the instance by passing in parameters.
At the end of an object life cycle call, the _ del _ method is called. you can think of _ del _ as a "destructor ". The following code shows the three methods:
From OS. path import joinclass FileObject: ''' wrap the file object to confirm that '''def _ init _ (self, filepath = '~ is disabled when the file stream is deleted '~ ', Filename='sample.txt'): # open a file self in read/write mode. file = open (join (filepath, filename), 'R + ') def _ del _ (self): self. file. close () del self. file
Control attribute access
Many people who switch from other languages to Python complain that it lacks the real encapsulation of classes. (There is no way to define private variables, and then define public getter and setter ). Python can be encapsulated by magic. Let's take a look:
_ Getattr _ (self, name ):
Defines the behavior when a user attempts to obtain a non-existent attribute. This applies to obtaining and redirecting common spelling errors, giving warnings when getting unrecommended attributes (you can calculate and give a value if you want), or processing an AttributeError. It is returned only when the call does not exist.
_ Setattr _ (self, name, value ):
Unlike _ getattr _ (self, name), __setattr _ is an encapsulated solution. Whether or not an attribute exists, it allows you to define a value assignment for the attribute, so that you can customize the attribute value. Avoid the error of "infinite recursion" when implementing _ setattr.
_ Delattr __:
It is the same as _ setattr _, but the function is to delete an attribute rather than set them. To avoid infinite recursion.
_ Getattribute _ (self, name ):
_ Getattribute _ defines the behavior when your attribute is accessed. In comparison, __getattr _ takes effect only when this attribute does not exist. Therefore, in the Python version that supports _ getattribute _, _ getattribute _ will be called before _ getattr _ is called __. _ Getattribute _ avoid the error of "infinite recursion. It should be noted that it is best not to implement _ getattribute __, because this practice is rarely seen and it is easy to produce bugs.
When defining attribute access control, it is likely to cause "infinite recursion ". The following code is used:
# Incorrect usage def _ setattr _ (self, name, value): self. name = value # whenever an attribute is assigned a value (such as self. name = value), ''_ setattr _ ()'' will be called, resulting in recursive calls. # This means that ''self. _ setattr _ ('name', value) ''is called, and each method calls itself. This will cause program crash. # Correct usage def _ setattr _ (self, name, value): self. _ dict _ [name] = value # assign a value to the attribute name in the class # customize special attributes
The magic method of Python is powerful, but you need to be careful when using it. it is very important to know the correct method of use.
Create custom container
There are many ways to make your Python class behavior the same as the built-in container type, such as list, dict, tuple, string, and so on. Python container types include variable types (such as list and dict) and immutable types (such as string and tuple). The difference between variable containers and immutable containers is that, once an unchangeable container is assigned a value, it cannot be modified.
Before creating a custom container, you should first understand the protocol. The protocol here is similar to the so-called "interface" in other languages. it gives you a lot of methods you must define. However, the protocol in Python is not formal and does not need to be explicitly declared for implementation. In fact, they are more like a guide.
Magic method of custom container
The following describes the magic methods that can be used to define a container. First, you can define _ len _ and _ getitem _ to implement an immutable container. (more will be discussed below ). Variable container protocol requires all non-variable containers, and also requires _ setitem _ and _ delitem __. If you want your object to be iterated, you need to define _ iter _ to return an iterator. The iterator must follow the iterator protocol and must have _ iter _ (return itself) and next.
_ Len _ (self ):
The length of the returned container. This is part of the variable and immutable container protocols.
_ Getitem _ (self, key ):
Defines the behavior produced by using self [key] when an item is accessed. This is also part of the immutable container and variable container protocols. If the key type is incorrect, a TypeError is generated. if the key does not have a proper value, a KeyError is generated.
_ Setitem _ (self, key, value ):
This method is called when you execute self [key] = value.
_ Delitem _ (self, key ):
Defines the action when a project is deleted (such as del self [key]). This is only part of the variable container protocol. An exception should be thrown when an invalid key is used.
_ Iter _ (self ):
Returns a container iterator. in many cases, the iterator is returned, especially when the built-in iter () method is called and when the for x in container is used: method loop. Iterators are their own objects. they must define the _ iter _ method for returning self.
_ Reversed _ (self ):
Implements the behavior when reversed () is called. The version after reverse sequence is returned. It is implemented only when the sequence can be ordered, for example, for list or tuples.
_ Contains _ (self, item ):
Defines the behaviors generated when calling in and not in to test whether a Member exists. You may ask why this is not part of the sequence protocol? When _ contains _ is not defined, if it is not defined, Python will iterate the elements in the container to compare them one by one, so as to return True or False.
_ Missing _ (self, key ):
This method is applicable to the dict Dictionary type, which defines the behavior triggered when the key cannot be found in the container. For example, if d = {'a': 1} and you execute d [notexist], d. _ missing _ ['notexist'] will be called.
One column
The following is an example in the book. it uses magic to implement a data structure in Haskell.
#-*-Coding: UTF-8-*-class FunctionalList: ''' implements the built-in list function and enriches other methods: head, tail, init, last, drop, take ''' def _ init _ (self, values = None): if values is None: self. values = [] else: self. values = values def _ len _ (self): return len (self. values) def _ getitem _ (self, key): return self. values [key] def _ setitem _ (self, key, value): self. values [key] = value def _ delitem _ (self, key): del self. values [key] def _ iter _ (self): return iter (self. values) def _ reversed _ (self): return FunctionalList (reversed (self. values) def append (self, value): self. values. append (value) def head (self): # obtain the first element return self. values [0] def tail (self): # obtain all elements after the first element return self. values [1:] def init (self): # obtain all elements before the last element return self. values [:-1] def last (self): # get the last element return self. values [-1] def drop (self, n): # obtain all elements except the first N return self. values [n:] def take (self, n): # obtain the first N elements return self. values [: n]
In fact, many similar implementations have been implemented in the collections module, such as Counter and OrderedDict.
Reflection
You can also control how to define the magic method using the built-in sisinstance () and issubclass () methods reflection. the magic method is:
_ Instancecheck _ (self, instance ):
Check whether an instance is an instance of the class you define
_ Subclasscheck _ (self, subclass ):
Check whether a class is a subclass of the class you define.
The use cases of these magic methods seem small and practical. they reflect some important things about object-oriented programs in Python, and in general Python: it is always a simple way to find something, even if it is unnecessary. these magic methods may not seem very useful, but once you need them, you will feel glad they exist.
Callable object
You may already know that in Python, methods are the most advanced objects. This means they can also be passed to methods, just like other objects. This is an amazing feature.
In Python, a special magic method can make the instance of the class behave like a function. you can call them and upload a function as a parameter to another function. This is a very powerful feature that makes Python programming more comfortable and sweet.
_ Call _ (self, [args...]):
Allows an instance of a class to be called like a function. Essentially, this means that x () is the same as x. _ call. Note that the _ call _ parameter is variable. This means that you can define _ call _ as other functions you want, regardless of the number of parameters.
_ Call _ is effective when the status of instances of those classes changes frequently. Calling this instance is a direct and elegant way to change the object state. It is better to use an instance to express it:
#-*-Coding: UTF-8-*-class Entity: "calls an object to change its position" def _ init _ (self, size, x, y): self. x, self. y = x, y self. size = sizedef _ call _ (self, x, y): "changing the position of an object" self. x, self. y = x, y
Context Management
The with statement is a keyword introduced from Python2.5. You should have met this code:
With open('foo.txt ') as bar:
# Do something with bar
In the with declaration code segment, we can start and exit some objects, and handle exceptions. This requires two magic methods: _ enter _ and _ exit __.
_ Enter _ (self ):
Defines the behavior that the session manager will generate when a block is initially created when the with statement is used. Note that the return value of __enter _ is bound to the target of the with statement or the name after the as statement.
_ Exit _ (self, exception_type, exception_value, traceback ):
Defines what the session manager should do when a code block is executed or terminated. It can be used to handle exceptions, perform cleanup, or perform daily work after some code blocks are executed. If the code block is successfully executed, prediction_type, prediction_value, and traceback are set to None. Otherwise, you can handle this exception or directly submit it to the user. If you want to handle this exception, make sure that _ exit _ returns True after all statements are completed. If you want the exception to be processed by the Session Manager, the exception will be generated.
Create an object descriptor
The descriptor is the class accessed when it is obtained, set, and deleted. Of course, other objects can also be changed. The descriptor is not independent. Instead, it means to be held by an owner class. When you create an object-oriented database or class that contains dependent documents, the descriptor is very useful. A typical method is to use different units to represent the same value or to indicate additional attributes of a data.
To become a descriptor, a class must at least have the _ get __,__ set __,__ delete _ method implemented:
_ Get _ (self, instance, owner ):
Defines the behavior when the descriptor value is obtained. Instance is an instance that owns the descriptor object. The owner is the owner.
_ Set _ (self, instance, value ):
Defines the behavior when the descriptor value is changed. Instance is an instance that owns the descriptor class. Value is the value to be set.
_ Delete _ (self, instance ):
Defines the action when the descriptor value is deleted. Instance is an instance that owns the descriptor object.
The following is an instance of the descriptor: unit conversion.
#-*-Coding: UTF-8-*-class Meter (object): "describer for units" meters "def _ init _ (self, value = 0.0): self. value = float (value) def _ get _ (self, instance, owner): return self. value def _ set _ (self, instance, value): self. value = float (value) class Foot (object): "describer for unit" feet "def _ get _ (self, instance, owner ): return instance. meter * 3.2808 def _ set _ (self, instance, value): instance. meter = float (value)/3.2808 class Distance (object): "represents the Distance between two descriptors using meters and inches" meter = Meter (10) foot = Foot ()
Use Time:
>>>d = Distance()>>>print d.foot>>>print d.meter32.80810.0
Copy
Sometimes, especially when you are dealing with mutable objects, you may want to copy an object and make some changes to it without affecting the original object. This is the role of Python copy.
_ Copy _ (self ):
Defines the behavior generated when you call copy. copy () for your class instance. Copy. copy () returns a small copy of your object -- this means that when the instance itself is a new instance, all its data is referenced -- for example, when an object is copied, its data is still referenced (therefore, changes to the data in the shortest copy may still lead to changes to the data in the original object ).
_ Deepcopy _ (self, memodict = {}):
Defines the behavior generated when you call copy. deepcopy () for your class instance. Copy. deepcopy () returns a deep copy of your object-the object and its data are copied. Memodict is a cache for previously copied objects-this optimizes the copy process and prevents infinite recursion when copying recursive data structures. When you want to make a deep copy of a separate attribute, call copy. deepcopy () and use memodict as the first parameter.
Appendix
Magic method for comparison