Skip to content

Instantly share code, notes, and snippets.

@pedramamini
Created February 15, 2012 06:43
Show Gist options
  • Save pedramamini/1833809 to your computer and use it in GitHub Desktop.
Save pedramamini/1833809 to your computer and use it in GitHub Desktop.
python: how to attach a function as a method instance to an arbitrary object.
# how to attach a function as a method instance to an arbitrary object.
class person:
def __init__ (self):
self.name = ""
def beast (self):
if self.name == "pedram":
return True
else:
return False
>>> pedram = person()
>>> pedram.name = "pedram"
>>> dave = person()
>>> dave.name = "dave"
>>> dave.beast()
False
pedram.beast()
True
def say (self, msg):
print self.name, msg
>>> pedram.say = types.MethodType(say, pedram)
>>> pedram.say("yeeehaaa")
pedram yeeehaaa
>>> dave.say("yeeehaaa")
Traceback (most recent call last):
File "<input>", line 1, in <module>
AttributeError: person instance has no attribute 'say'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment