Skip to content

Instantly share code, notes, and snippets.

@durden
Created November 13, 2012 21:32
Show Gist options
  • Save durden/4068540 to your computer and use it in GitHub Desktop.
Save durden/4068540 to your computer and use it in GitHub Desktop.
Just experimenting with weird stuff like monkey patching base object to do evil stuff
class myobject(object):
ATTR_CACHE = {}
def __init__(self, *args, **kwargs):
for arg in args:
print arg
super(myobject, self).__init__(*args, **kwargs)
def __new__(cls, *args, **kwargs):
# At this point cls is NOT created, it's just a string :)
print 'create instance of', cls
# Could put this in __init__ to save off with values
for arg in args:
cls.ATTR_CACHE[arg] = None
for k, v in kwargs.iteritems():
cls.ATTR_CACHE[k] = v
# Must return instance of cls or __init__ won't be called
return super(myobject, cls).__new__(cls, *args, **kwargs)
# Must replace the builtins instance so entire environment will get this weird
# implementation no matter what
__builtins__['object'] = myobject
# Now ANY class inheriting from object will actually inheirt from myobject :)
# To prove it to yourself import this code from a module, then create a class
# and inherit from object. You'll notice you have an ATTR_CACHE attribute...
# that is shared between ALL objects created from now on.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment