写代码的小孩

苦逼op 快乐地写代码

Prototype pattern (Python recipe)

原文链接:http://code.activestate.com/recipes/86651-prototype-pattern/

http://dongweiming.github.io/python-pototype.html

from copy import deepcopy

class Prototype:
    def __init__(self):
        self._objs = {}
        
    def registerObject(self, name, obj):
        """
        register an object.
        """
        self._objs[name] = obj
        
    def unregisterObject(self, name):
        """unregister an object"""
        del self._objs[name]
        
    def clone(self, name, **attr):
        """clone a registered object and add/replace attr"""
        obj = deepcopy(self._objs[name])
        obj.__dict__.update(attr)
        return obj
    

if __name__ == '__main__':
    class A:
        pass


    a=A()
    prototype=Prototype()
    prototype.registerObject("a",a)
    b=prototype.clone("a",a=1,b=2,c=3)


    # 这里会返回对象a
    print(a)
    # 这里的对象其实已经被修改成(1, 2, 3)
    print(b.a, b.b, b.c)


阅读更多
文章标签: prototype python
上一篇coverage.py的覆盖率统计原理
下一篇strategy pattern in Python
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭