Advertisement
Guest User

Untitled

a guest
Sep 27th, 2016
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. # There are a dozen ways to implement the Prototype or Properties Pattern in Python.
  2. #
  3. # You could use copy.copy(), or program with classes and classmethods only for example.
  4. #
  5. # But if you want to use an existing library in this style, and don't want to loose
  6. # Python's flexibility (multiple inheritance, etc) I believe this solution works best.
  7. #
  8. # Prototypes, in Pythonic terms, are objects that behave like instances and classes/types,
  9. # unifying instantiation and inheritance. So the most obvious solution, even if wasteful,
  10. # is to have a thin layer over a type and it's single instance.
  11.  
  12. import attr
  13.  
  14. class BaseObject:
  15. """ Could be any class that you want to adapt to the prototyped style
  16. """
  17. def __init__(self, **kw):
  18. self.__dict__.update(kw)
  19.  
  20.  
  21. @attr.s
  22. class PObject:
  23. ptype = attr.ib(default=None)
  24. pinstance = attr.ib(default=object)
  25. def clone(self, name):
  26. new_ptype = type(name, (self.ptype or BaseObject,), {})
  27. new_pinstance = new_ptype(**self.pinstance.__dict__)
  28. return PObject(new_ptype, new_pinstance)
  29. def __getattr__(self, name):
  30. return getattr(self.pinstance, name)
  31. ## TODO: setattr, repr, etc
  32.  
  33. # Root object
  34. Object = PObject().clone('Object')
  35.  
  36. ### Example
  37. person = Object.clone('person')
  38. person.name = 'John Doe'
  39. person.arms = 2
  40.  
  41. # Anna retains the number of arms of its parent
  42. person1 = person.clone('person1')
  43. person1.name = 'Anna Doe'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement