Skip to content

Instantly share code, notes, and snippets.

@cbare
Created January 31, 2013 01:07
Show Gist options
  • Select an option

  • Save cbare/4678963 to your computer and use it in GitHub Desktop.

Select an option

Save cbare/4678963 to your computer and use it in GitHub Desktop.
How to get a dynamic object in Python. A dynamic object is just a bag of properties, some of which might happen to be functions, just like objects in javascript. Forget OOP. This is QDP - quick-n-dirty programming!
class Dynamic(dict):
"""Dynamic objects are just bags of properties, some of which may happen to be functions"""
def __init__(self, **kwargs):
self.__dict__ = self
self.update(kwargs)
def __setattr__(self, name, value):
import types
if isinstance(value, types.FunctionType):
self[name] = types.MethodType(value, self)
else:
super(Dynamic, self).__setattr__(name, value)
d = Dynamic(flapdoodle='thingamajig')
d.whatsit = "dammit!"
print d['whatsit']
# dammit!
print d.whatsit
# dammit!
print d['flapdoodle']
# thingamajig
print d.flapdoodle
# thingamajig
d.whatsit = 'foo'
print d['whatsit']
# foo
print d.whatsit
# foo
def spam(self, n):
for i in range(n):
print "The %s is in the %s!!" % (self.whatsit, self.flapdoodle,)
d.spam = spam
d.spam(5)
# The foo is in the thingamajig!!
# The foo is in the thingamajig!!
# The foo is in the thingamajig!!
# The foo is in the thingamajig!!
# The foo is in the thingamajig!!
print str(d)
# {'flapdoodle': 'thingamajig', 'whatsit': 'foo', 'spam': <bound method ?.spam of {...}>}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment