Python metaclass instructions

  • 2020-04-02 09:29:59
  • OfStack

I want a whole bunch of classes with a single feature, how do I add to them? Template template? Why don't I just create a bunch of classes from this template? Then you need metaclasses. Flash"

Define a metaclass (template for just one class! And remember this is at the class level, not at the object level!) :
 
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 metaclass. Is a template for a class.

Where is it to be used? It's going to be used in a class as a template for that class.

What does it do? A template is to provide some common characteristics.

What characteristics does this class provide? Two features, one. Type the name of the class after the class definition (s). 2. Format the print class (s).

Exactly how to work, open your interpreter, type in the above code, and hit the road:

Input:

The class MyClass (object) :
__metaclass__ = MyMeta

When entering the end of the class definition, output:
MyClass
MyClass

See, hoho! It turns out that it does initialize a class, not an object!! This is the first feature.

The second:

Input:

Print MyClass
Output:

Beautiful class MyClass

Aha, just right, as we expected!! Of course you can personalize your class any way you want!!

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

Let's implement a Singleton pattern (from the woodpecker community) :

The Singleton metaclass:
 
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 

Very simple design pattern, I believe you can understand what is going on!
 
class MyClass(object): 
__metaclass__ = Singleton 
def __init__(self,arg): 
self.arg = arg 

The class that USES the Singleton metaclass.

Is there only one instance? That can only see, deng grandpa said well: practice is the only criterion to test the truth. - the essence!
 
>>> my1 = MyClass("hello") 
>>> my2 = MyClass("world") 
>>> my1 is my2 
True 
>>> my1.arg 
'hello' 
>>> my2.arg 
'hello' 

Our attempt to create my2 failed, which is proof that we succeeded.

In fact, metaclasses are not used much, understanding understanding. Agains!!!!!

Related articles: