Created
May 21, 2014 12:31
-
-
Save fginter/0bd2446da31b3b3a7a58 to your computer and use it in GitHub Desktop.
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
# Get some code that does something in a class. Note that the code is a string. | |
code=""" | |
def to_string(self): | |
print "x=", self.x | |
""" | |
# Print that code into a temporary Python module | |
with open("zzz.py","wt") as py: | |
print >> py, code | |
# Now import that | |
from zzz import to_string | |
#What did we get? | |
print "to_string is:", to_string | |
#Can we actually smuggle this as a method into a class? Of course! | |
#Here's the victim: | |
class SomeObject: | |
def __init__(self,x): | |
self.x=x | |
#...and here we just add a method on the fly | |
SomeObject.to_string=to_string | |
#Make an object | |
o1=SomeObject(1) | |
#Lo and behold! It works! | |
o1.to_string() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment