Skip to content

Instantly share code, notes, and snippets.

@TheFeshy
Created March 31, 2012 17:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheFeshy/2266871 to your computer and use it in GitHub Desktop.
Save TheFeshy/2266871 to your computer and use it in GitHub Desktop.
Dynamically add "convenience" functions from a dictionary of values
class A(object):
items = {"one":1,
"two":2}
def __init__(self):
self.item = 0
for key in A.items:
f = lambda self,k=key:(self.__setattr__("item", self.items[k]),self)[1]
f.__name__=key
setattr(A,key,f)
a = A()
print a.one() #Prints the a object
print a.item #prints "1"
print a.two() #prints the a object
print a.item #prints "2"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment