I want a large group of classes to have one feature, how can I add them? Template template, I create a bunch of classes from this template not just OK? That would require a meta class. Rattling
Define a meta class (on the template for a class!) Don't think, remember this is class level, not object level! ):
Copy Code code 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? Ah, this is a meta class. is a template for a class.
Where is it going to be used? It needs to be used in a class as a template for this class.
What role does it play? Template is to provide some common features.
What characteristics does this class provide? Two characteristics, 1. The name of the class to print after the class is defined (__init__). 2. Print the format of the Class (__STR__).
In the end how to work, open your interpreter, enter the above code, go:
Input:
Class MyClass (object):
__metaclass__ = Mymeta
When a carriage return ends the definition of a class, the output:
MyClass
MyClass
Got it, rattling! It turns out that it really is initializing a class, not an object!!!!! This is the first feature.
The second one:
Input:
Print MyClass
Output:
Beautiful class MyClass
Aha, that's right, as we expected,!!!!!!!!. Of course you can personalize your class arbitrarily!!
####################################################################################
Here we implement a singleton pattern (from the Woodpecker community):
Singleton Meta class:
Copy Code code 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 pattern, I believe you can understand what is going on!
Copy Code code as follows:
Class MyClass (object):
__metaclass__ = Singleton
def __init__ (Self,arg):
Self.arg = arg
A class that uses the Singleton class.
Is it possible to have only one instance?? That can only be seen, Grandpa Deng said good: practice is the only criterion of truth test. --The essence!!
Copy Code code as follows:
>>> my1 = MyClass ("Hello")
>>> my2 = MyClass ("World")
>>> My1 is My2
True
>>> My1.arg
' Hello '
>>> My2.arg
' Hello '
Our attempt to create My2 failed, and it just proves that we have succeeded.
In fact, the Meta class is not much used, understand understanding. Rattling!!