I want a large group of classes that all have one characteristic, how do I add it to them? A template template, from which I create a bunch of classes? That would require metaclasses. Hoho.
Define a metaclass (a template for a class! Don't think too much about it, and remember that it's at the class level, not the object level!) Remember that this is at the class level, not the object level!
Copy Code The code is as follows.
class MyMeta(type):
def __init__(cls,name,bases,dic):
print cls.__name__
print name
def __str__(cls):return 'Beautiful class %s'%cls.__name__
What is this thing? Ha, it's a metaclass. It's a class template.
Where is it going to be used? It's going to be used in a class as a template for that class.
What role does it play? A template, that is, provides some common characteristics.
What features does this class provide? Two features, 1. Prints the name of the class (__init__) after the class is defined. 2. Prints the format of the class (__str__).
How exactly does it work, open your interpreter, enter the code above and hit the road:
Input:
class MyClass(object):
__metaclass__ = MyMeta
Output when a carriage return ends the class definition:
MyClass
MyClass
Get the picture, hoho! Turns out it does initialize a class, not an object !!!!! This one is the first feature.
The second one:
Input:
print MyClass
Output:
Beautiful class MyClass
Aha, just right, as we expected !!!!!!!! Of course you can personalize your class any way you want!
####################################################################################
Here we implement a Singleton pattern (from the Woodpecker community):
Singleton metaclass:
Copy Code The code is as follows.
class Singleton(type):
def __init__(cls,name,bases,dic):
super(Singleton,cls).__init__(name,bases,dic)
= None
def __call__(cls,*args,**kwargs):
if is None:
= super(Singleton,cls).__call__(*args,**kwargs)
return
A very simple design pattern, I'm sure you can see what's going on!
Copy Code The code is as follows.
class MyClass(object):
__metaclass__ = Singleton
def __init__(self,arg):
= arg
Classes that use the Singleton metaclass.
Is there only one example? That can only be seen, practice is the only test of truth. -Essence!
Copy Code The code is as follows.
>>> my1 = MyClass("hello")
>>> my2 = MyClass("world")
>>> my1 is my2
True
>>>
'hello'
>>>
'hello'
Our attempt to create my2 failed, which just proves that we succeeded.
Actually, the meta class is not used much, understand understand understand. Hoho!