Python原型模式

原型模式,实例提供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原型模式)