How to use Magic method to realize attribute Monitoring in python
Today, I will talk to you about how to use magic methods to achieve attribute monitoring in python, many people may not know much about it. In order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.
First, the use of magic methods to achieve attribute monitoring
Here, we learn a few necessary magic methods.
The _ _ getattr__ magic method is used to trigger the acquisition of member variables of the class. Distinguish between _ _ getitem__
The _ _ setattr__ magic method, which is triggered when the member variable of the class is set. Distinguish between _ _ setitem__
The _ _ delattr__ magic method, which is used to monitor when a member variable of a class is deleted. Distinguish between _ _ delitem__
Second, example: custom class to implement attribute monitoring
We need to implement a monitoring of the properties of the fangkuai class.
Implementation steps:
1. Set up custom classes.
two。 Initializes the properties of the class.
3. Write the magic method _ _ setattr__ method, the first parameter key is the name of the custom property, and the second parameter is the value of the property. Note that this custom attribute can be used to outline the properties of the class with your own mindset.
4. Write the magic method _ _ getattr__ method, and the item parameter is the name of the property being monitored.
5. Write the magic method _ _ delattr__ method, where the item parameter is the name of the property being deleted.
After reading the above, do you have any further understanding of how to use magic methods to implement attribute monitoring in python? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.