Skip to content

Instantly share code, notes, and snippets.

@drhanlau
Last active March 4, 2016 07:30
Show Gist options
  • Save drhanlau/ce58624c641b78c6747b to your computer and use it in GitHub Desktop.
Save drhanlau/ce58624c641b78c6747b to your computer and use it in GitHub Desktop.
Main part of prototype_pattern.py
class Book:
def __init__(self, name, authors, price, **rest):
'''Examples of rest: publisher, length, tags, publication date'''
self.name = name
self.authors = authors
self.price = price
self.__dict__.update(rest)
def __str__(self):
mylist=[]
ordered = OrderedDict(sorted(self.__dict__.items())) for i in ordered.keys():
if i == 'price': mylist.append('RM ')
mylist.append('{}: {}'.format(i, ordered[i]))
mylist.append('\n') return ''.join(mylist)
def 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 structures'))
prototype = Prototype()
cid = 'k&r-first'
prototype.register(cid, b1)
b2 = prototype.clone(cid, name='The C Programming Language (ANSI)', price=48.99, length=274, publication_date='1988-04-01', edition=2)
for i in (b1, b2):
print(i)
print("ID b1 : {} != ID b2 : {}".format(id(b1), id(b2)))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment