Home  >  Article  >  Backend Development  >  Python 元类使用说明

Python 元类使用说明

WBOY
WBOYOriginal
2016-06-16 08:47:16992browse

我要一大群的类都具有一中特点,我怎么给他们加上呢?模板模板吗,我从这个模板创建一群类不就OK了?那就需要元类了。霍霍》

定义一个元类(就所一个类的模板!莫多想,还要记住这是类级别的,不是对象级别的!):

复制代码 代码如下:

class MyMeta(type):
def __init__(cls,name,bases,dic):
print cls.__name__
print name
def __str__(cls):return 'Beautiful class %s'%cls.__name__

这是个什么东西?哈,这是个元类。是个类的模板。

它要用在哪里?它要用在一个类里,作为这个类的模板。

起的什么作用?模板,就是提供一些共同的特征。

这个类提供了什么样的特征?两个特征,1。类定义后打印类的名字(__init__)。2。打印类的格式(__str__)。

到底回怎么工作,打开的你的解释器,输入以上的代码,上路:

输入:

class MyClass(object):
__metaclass__ = MyMeta

回车结束类的定义时,输出:
MyClass
MyClass

明白了吧,霍霍!事实证明它确实是初始化一个类,而不是一个对象!!!!!这个是第一个特征。

第二个:

输入:

print MyClass
输出:

Beautiful class MyClass

啊哈,恰如其分,如我们所预料的那样!!!!!!!!当然你可以任意个性化你的类!!

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

下面我们来实现一个Singleton模式(来自啄木鸟社区):

Singleton元类:
复制代码 代码如下:

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

非常简单的一个设计模式,相信你能明白是怎么回事!
复制代码 代码如下:

class MyClass(object):
__metaclass__ = Singleton
def __init__(self,arg):
self.arg = arg

使用了Singleton元类的类。

是不是只能有一个实例呢??那只能看看了,邓爷爷说的好:实践是检验真理的唯一标准。——精华!!
复制代码 代码如下:

>>> my1 = MyClass("hello")
>>> my2 = MyClass("world")
>>> my1 is my2
True
>>> my1.arg
'hello'
>>> my2.arg
'hello'

我们创建my2的尝试失败了,而这恰恰证明我们成功了。

其实元类用的不多,理解理解。霍霍!!
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn