《精通Python设计模式》学习之原型模式
生活随笔
收集整理的這篇文章主要介紹了
《精通Python设计模式》学习之原型模式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
暫時在工作中,還沒有用到呢~~~
以后要留意一下,主要用于復制對象副本,
然后又有自定義屬性的地方。
import copy from collections import OrderedDictclass Book:def __init__(self, name, authors, price, **rest):self.name = nameself.authors = authorsself.price = priceself.__dict__.update(rest)def __str__(self):mylist = []ordered = OrderedDict(sorted(self.__dict__.items()))for i in ordered.keys():mylist.append('{}: {}'.format(i, ordered[i]))if i == 'price':mylist.append('$')mylist.append('\n')return ''.join(mylist)class Prototype:def __init__(self):self.objects = dict()def register(self, identifier, obj):self.objects[identifier] = objdef unregister(self, identifier):del self.objects[identifier]def clone(self, identifier, **attr):found = self.objects.get(identifier)if not found:raise ValueError('Incorrect object identifier: {}'.format(identifier))obj = copy.deepcopy(found)obj.__dict__.update(attr)return objdef main():b1 = Book('The C Programming Language', ('Brian W. Kernighan', 'Dennis M. Ritchie'),price=118, publisher='Prentice Hall', length=228, publication_date='1978-02-22',tags=('C', 'programming', 'algorithms', 'data stuctures'))prototype = Prototype()cid = 'k&r-first'prototype.register(cid, b1)b2 = prototype.clone(cid, name='The C Programming Language(ANSI', price=48.99,publisher='Prentice Hall', length=274, publication_date='1988-05-01', edition=2)for i in (b1, b2):print(i)print("ID b1 : {} != ID b2 : {}".format(id(b1), id(b2)))if __name__ == '__main__':main()轉載于:https://www.cnblogs.com/aguncn/p/9413565.html
總結
以上是生活随笔為你收集整理的《精通Python设计模式》学习之原型模式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java中线程的6种状态
- 下一篇: jacky解读麻省理工《计算机科学与Py