Skip to content

Instantly share code, notes, and snippets.

@yuu-ito
Last active December 6, 2016 11:33
Show Gist options
  • Save yuu-ito/d9d2058edbf7dbec8d2895cecfe8f39f to your computer and use it in GitHub Desktop.
Save yuu-ito/d9d2058edbf7dbec8d2895cecfe8f39f to your computer and use it in GitHub Desktop.
pythonでメタプログラミング
# 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')
@yuu-ito
Copy link
Author

yuu-ito commented Dec 6, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment