Last active
December 6, 2016 11:33
-
-
Save yuu-ito/d9d2058edbf7dbec8d2895cecfe8f39f to your computer and use it in GitHub Desktop.
pythonでメタプログラミング
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
# https://docs.python.org/3.5/library/types.html | |
from types import MethodType | |
class Base(object): | |
def __init__(self, **kwargs): | |
self.__dict__.update(kwargs) | |
def add_instance_method(self, method): | |
setattr(self, method.__name__, MethodType(method, self)) | |
p0 = Base(name="zero") | |
p0.say() # --> AttributeError: 'Base' object has no attribute 'say' | |
def say(self): | |
return "%s: hi." % self.name | |
p1 = Base(name="taro") | |
p1.add_instance_method(say) | |
p1.say() # --> 'taro: hi.' | |
def say(self): | |
return "%s: hello" % self.name | |
p2 = Base(name="jiro") | |
p2.add_instance_method(say) | |
(p1.say(), p2.say()) # --> ('taro: hi.', 'jiro: hello') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://docs.python.org/3.5/library/types.html