Read a document, learn from it! Write down your understanding of the Python meta-class, and welcome the great God to give you advice.
My understanding is that
The type is used to create a meta-class, which is used to create the class used to create an instance
In such a way, is it possible to think that the process of creating a class with a meta class is equivalent to creating an instance of a class, the class creates a different instance, although each instance has a similar property, method, but is not the same!
classFruits ():def __init__(self,name,color): Self.name=name Self.color=Colordef __new__(cls,name,color):returnObject.__new__(CLS) Apple=fruits ('Apple','Red')Print(Apple.name)Print(apple.color) Banana=fruits ('Banana','Yellow')Print(Banana.name)Print(Banana.color)
The two instances of the class Apple,banana all have the same property name,age, but the respective values are really different, belong to the fruit category, but are different fruits.
Then look at the process of the meta-class custom class, directly refer to the code of the Great God
A meta-class can also be thought of as having the same place for each class (for example, a meta-class creation, a common Fu class), and a different place (the class name of each class is different, and the method is implemented differently)
#conjecture, the new method in the class is used to create an instance of the#The new method of the meta-class is used to create the class? #daosh: Incoming typeclassSaymetaclass (type):#incoming three eternal propositions: Class name, parent class, attribute def __new__(CLS, name, bases, attrs):Print("test, New is running!") #create "talent"attrs['Say_'+ Name] =LambdaSelf, value, Saying=name:Print(Saying +','+ Value +'!') #inheriting three eternal propositions: Class name, parent class, attribute returnType.__new__(CLS, name, bases, Attrs)######## #Hello类#Life Two: Create a classclassHello (Object, metaclass=saymetaclass):Pass#Two birth three: Create a real columnHello =Hello ()#Sansheng All things: invoking instance methodsHello.say_hello ('world!')######## #Nihao类#Life Two: Create a classclassNihao (Object, metaclass=saymetaclass):Pass#Two birth three: Create a real columnNihao =Nihao ()#Sansheng All things: invoking instance methodsNihao.say_nihao ('world!')
This is the process of creating a class with a meta-class, with Class Hello (object, Metaclass=saymetaclass): Creating classes, calling the __new__ method of the meta-class at creation time (it seems to find a continuity: The new method of the class is used to create the instance, The new method of the meta-class is used to create a class. The class hello and Nihao,hello have a private custom say_** method with the new method of the Meta class, is it a bit similar to the instance of the class, it feels much simpler to understand.
Article Link: http://python.jobbole.com/88795/
Understanding the meta-class of Python