Created
February 15, 2012 06:43
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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