A metadatabase is a template of a class. It performs behavior at the class level.
The following uses metadata to implement the singleton design mode (design mode 9 adopts another method ):
[Python]
<P> from warnings import * </P>
From warnings import *
[Python]
Class SingletonMeta (type ):
_ Instance = None
_ Mutex = threading. Lock ()
Def _ init _ (cls, name, bases, dic ):
Super (SingletonMeta, cls). _ init _ (name, bases, dic)
Cls. _ instance = None
If '_ str _' not in dic:
# Raise TypeError ("class requires overriding of _ str __()")
Warn ("class '% s' requires overriding of _ str _ () \ n" % name, stacklevel = 3)
Def _ call _ (cls, * args, ** kwargs ):
If cls. _ instance is None:
Cls. _ mutex. acquire ()
If cls. _ instance is None:
Cls. _ instance = super (SingletonMeta, cls). _ call _ (* args, ** kwargs)
Else:
Cls. _ instance. _ init _ (* args, ** kwargs)
Cls. _ mutex. release ()
Else:
Cls. _ instance. _ init _ (* args, ** kwargs)
Return cls. _ instance
Class Single (object ):
_ Metaclass _ = SingletonMeta
Def _ init _ (self, name ):
Print (name)
Def _ str _ (self ):
Return self. _ class _. _ name __
# Client
If (_ name __= = "_ main __"):
Singleton1 = Single ("hello ")
Singleton2 = Single ("world ")
If singleton1 is singleton2:
Print ("they are the same object of class '% S'" % singleton1)
Class SingletonMeta (type ):
_ Instance = None
_ Mutex = threading. Lock ()
Def _ init _ (cls, name, bases, dic ):
Super (SingletonMeta, cls). _ init _ (name, bases, dic)
Cls. _ instance = None
If '_ str _' not in dic:
# Raise TypeError ("class requires overriding of _ str __()")
Warn ("class '% s' requires overriding of _ str _ () \ n" % name, stacklevel = 3)
Def _ call _ (cls, * args, ** kwargs ):
If cls. _ instance is None:
Cls. _ mutex. acquire ()
If cls. _ instance is None:
Cls. _ instance = super (SingletonMeta, cls). _ call _ (* args, ** kwargs)
Else:
Cls. _ instance. _ init _ (* args, ** kwargs)
Cls. _ mutex. release ()
Else:
Cls. _ instance. _ init _ (* args, ** kwargs)
Return cls. _ instance
Class Single (object ):
_ Metaclass _ = SingletonMeta
Def _ init _ (self, name ):
Print (name)
Def _ str _ (self ):
Return self. _ class _. _ name __
# Client
If (_ name __= = "_ main __"):
Singleton1 = Single ("hello ")
Singleton2 = Single ("world ")
If singleton1 is singleton2:
Print ("they are the same object of class '% S'" % singleton1)
Running result:
Hello
World
They are the same object of class 'singles'