类设计模式python学习~元类
废话就不多说了,开始。。。
元类是类的模版,在类的层次上标准类的行为。
面下用使元类现实单例设计模式(设计模式九 采取的是另一种方法):
from warnings import *
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__ #客户端 if(__name__=="__main__"): singleton1=Single("hello") singleton2=Single("world") if singleton1 is singleton2: print("they are the same object of class '%s'"%singleton1)
运行结果:
hello
world
they are the same object of class 'Single'
文章结束给大家分享下程序员的一些笑话语录:
有一天,一个男人穿越森林的时候,听到一个细微的声音叫住他。他低头一看,是一只青蛙。
“如果你亲我一下,我会变成一个美丽的公主哦。”男人一言不发,把青蛙捡起来,放入口袋。
“如果你亲我一下,我会变成一个美丽的公主哦。而且,我会告诉我遇到的每一个人,你是多么聪明和勇敢,你是我的英雄。”男人把青蛙拿出来,对着它微微一笑,又把它放回口袋。
“如果你亲我一下,我会变成一个美丽的公主,然后我愿意成为你的爱人一星期。”男人又把青蛙拿出来,对着它微微一笑,把它放回口袋。
“如果你亲我一下,我会变成一个美丽的公主,然后我愿意成为你的爱人一年,而且你可以对我做任何事。”再一次,男人把青蛙拿出来,对着它微微一笑,又把它放回口袋。
最后,青蛙无力地问:“我开出了这么好的条件,为什么你还不肯吻我?”男人说:“我是一个程序员,我可没时间和什么公主鬼混。不过,拥有一个会说话的青蛙,倒是蛮酷的。”