Skip to content

Instantly share code, notes, and snippets.

@kashifrazzaqui
Created October 13, 2010 13:38
Show Gist options
  • Save kashifrazzaqui/624043 to your computer and use it in GitHub Desktop.
Save kashifrazzaqui/624043 to your computer and use it in GitHub Desktop.
class PrototypeStore(dict):
def __setattr__(self, name, value):
self[name] = value
def __getattr__(self, name):
return self[name]
class PrototypeMeta(type):
def __new__(metacls, cls_name, bases, attrs):
cls = type.__new__(metacls, cls_name, bases, attrs)
cls.prototype = PrototypeStore()
return cls
class Prototype(object):
__metaclass__ = PrototypeMeta
def __getattr__(self, name):
return self.__class__.prototype[name]
class TestClass(Prototype):
def __init__(self):
self.a = 10
def run():
first = TestClass() # Make an object
first.prototype.x = 7 # Assign 'x' to its prototype
second = TestClass() # Create another object of the same class
print second.x # This should print 7, which was assigned to an earlier object
first.x = 9 # Now lets overwrite 'x' with a local value
print first.x # This should return 9 and not 7
del first.x # Removing this should cause a reference back to the 'x' in prototype
print first.x # This should return 7
first.prototype.incr = lambda x: x + 1 # Lets try this for functions
print second.incr(10) # This should return 11
if __name__ == '__main__':
run()
@dahlia
Copy link

dahlia commented Oct 14, 2010

Good work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment