Python uses the MethodType binding method to the class sample code, pythonmethodtype
Preface
This article describes how to bind a method of MethodType to a class in python. I will share the content for your reference. I will not talk about it here. Let's take a look at the detailed introduction:
If you are not familiar with MethodType in python, read this article first.
Problem cause
Let's take a look at the following code:
From types import MethodType def set_age (self, age): self. age = age class Stu (object): pass Stu. set_age = MethodType (set_age, Stu) A = Stu () B = Stu (). set_age (10) B. set_age (15) print (. age, B. age) # The result is 15.
Run this code and we will find that the output results are all 15. We set the attribute values of object A and object B respectively. Why? At first, I had the same question. Later I found that I did not have enough understanding of MethodType. After verification, I got the following explanation.
Analysis
The Stu class does not have any attributes or methods. Therefore, instances created using this class do not have any attributes or methods. Use MethodType to bind the set_age Method to the Stu class. Instead of writing the method directly to the Stu class, create a link pointing to the external method in the Stu memory, the link is also copied when you create an Stu instance. Therefore, no matter how many instances are created, these instances and Stu classes point to the same set_age method.A.set_age(10)Instead of creating the age attribute inside the instance A, the age attribute is created in the memory area of the external set_age method. Because the link between A and B points to the memory area of the external set_age method, whether A or B calls the set_age method, it changes the age attribute in the memory area of the set_age method, therefore, if A changes B, the new instance C will also have the age attribute without calling the set_age method, because the link of C points to the memory zone of the set_age method, set_age was called by A or B before.
Summary
It means that the property set through this binding method is a bit of a static variable in java.
Well, the above is all the content of this article. I hope the content of this article will help you in your study or work. If you have any questions, you can leave a message, thank you for your support.