The meta-class is the template of the class-it's too vivid, Hook. I want a large group of classes to have a unique feature. how can I add them? Template? isn't it okay for me to create a group of classes from this template? The metadata is required. Hook
Define a metadata class (just a template of the class! Don't think about it. remember that this is a class level, not an object level !) :
The code is as follows:
Class MyMeta (type ):
Def _ init _ (cls, name, bases, dic ):
Print cls. _ name __
Print name
Def _ str _ (cls): return 'beauul ul class % s' % cls. _ name __
What is this? Ha, this is a metadata class. Is a class template.
Where should I use it? It must be used in a class as a template for this class.
What role does it play? A template provides common features.
What features does this class provide? Two features: 1. After the class is defined, print the class name (_ init __). 2. The format of the print class (_ str __).
In the end, how does one work? open your interpreter, enter the above code, and go on the road:
Input:
Class MyClass (object ):
_ Metaclass _ = MyMeta
When you press enter to end the class definition, the output is:
MyClass
MyClass
You understand, hook! It turns out that it is indeed initializing a class, not an object !!!!! This is the first feature.
Second:
Input:
Print MyClass
Output:
Beautiful class MyClass
Aha, as we expected !!!!!!!! Of course, you can personalize your class at will !!
######################################## ######################################## ####
Next we will implement a Singleton mode (from the woodpecker community ):
Singleton meta class:
The code is as follows:
Class Singleton (type ):
Def _ init _ (cls, name, bases, dic ):
Super (Singleton, cls). _ init _ (name, bases, dic)
Cls. instance = None
Def _ call _ (cls, * args, ** kwargs ):
If cls. instance is None:
Cls. instance = super (Singleton, cls). _ call _ (* args, ** kwargs)
Return cls. instance
A very simple design model. I believe you can understand what is going on!
The code is as follows:
Class MyClass (object ):
_ Metaclass _ = Singleton
Def _ init _ (self, arg ):
Self. arg = arg
The Singleton Metadatabase class is used.
Is there only one instance ?? We can only look at it. Grandpa Deng said: Practice is the only criterion for truth testing. -- Excellent !!
The code is as follows:
>>> My1 = MyClass ("hello ")
>>> My2 = MyClass ("world ")
>>> My1 is my2
True
>>> My1.arg
'Hello'
>>> My2.arg
'Hello'
The attempt to create my2 fails, and this proves that we have succeeded.
In fact, meta classes are not used much, so you can understand them. Hook !!