美文网首页
Python原型模式

Python原型模式

作者: 虾想家 | 来源:发表于2017-03-18 14:34 被阅读14次

    原型模式,实例提供clone方法,获取与当前相同的实例,并允许设置新的参数。

    class ProtoType(object):
        def __init__(self):
            super().__init__()
            self.setting_a = "a"
            self.setting_b = "b"
    
        def clone(self, **kwargs):
            import copy
            obj = copy.deepcopy(self)
            obj.__dict__.update(**kwargs)
            return obj
    
    
    def main():
        prototype = ProtoType()
        prototype_diff = prototype.clone(setting_a="x", setting_b="y")
        print(prototype_diff.setting_a, prototype_diff.setting_b)
        print("id_prototype", id(prototype), "id_prototype_diff", id(prototype_diff))
    
    
    if __name__ == '__main__':
        main()
    

    相关文章

      网友评论

          本文标题:Python原型模式

          本文链接:https://www.haomeiwen.com/subject/sfbunttx.html