Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # There are a dozen ways to implement the Prototype or Properties Pattern in Python.
- #
- # You could use copy.copy(), or program with classes and classmethods only for example.
- #
- # But if you want to use an existing library in this style, and don't want to loose
- # Python's flexibility (multiple inheritance, etc) I believe this solution works best.
- #
- # Prototypes, in Pythonic terms, are objects that behave like instances and classes/types,
- # unifying instantiation and inheritance. So the most obvious solution, even if wasteful,
- # is to have a thin layer over a type and it's single instance.
- import attr
- class BaseObject:
- """ Could be any class that you want to adapt to the prototyped style
- """
- def __init__(self, **kw):
- self.__dict__.update(kw)
- @attr.s
- class PObject:
- ptype = attr.ib(default=None)
- pinstance = attr.ib(default=object)
- def clone(self, name):
- new_ptype = type(name, (self.ptype or BaseObject,), {})
- new_pinstance = new_ptype(**self.pinstance.__dict__)
- return PObject(new_ptype, new_pinstance)
- def __getattr__(self, name):
- return getattr(self.pinstance, name)
- ## TODO: setattr, repr, etc
- # Root object
- Object = PObject().clone('Object')
- ### Example
- person = Object.clone('person')
- person.name = 'John Doe'
- person.arms = 2
- # Anna retains the number of arms of its parent
- person1 = person.clone('person1')
- person1.name = 'Anna Doe'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement