Skip to content

Instantly share code, notes, and snippets.

@yuu-ito
Last active December 6, 2016 11:33
Show Gist options
  • Select an option

  • Save yuu-ito/d9d2058edbf7dbec8d2895cecfe8f39f to your computer and use it in GitHub Desktop.

Select an option

Save yuu-ito/d9d2058edbf7dbec8d2895cecfe8f39f to your computer and use it in GitHub Desktop.

Revisions

  1. yuu-ito revised this gist Dec 6, 2016. 1 changed file with 3 additions and 3 deletions.
    6 changes: 3 additions & 3 deletions dynamic_typing.py
    Original file line number Diff line number Diff line change
    @@ -4,7 +4,7 @@ class Base(object):
    def __init__(self, **kwargs):
    self.__dict__.update(kwargs)

    def add_eigen_method(self, method):
    def add_instance_method(self, method):
    setattr(self, method.__name__, MethodType(method, self))


    @@ -17,7 +17,7 @@ def say(self):


    p1 = Base(name="taro")
    p1.add_eigen_method(say)
    p1.add_instance_method(say)
    p1.say() # --> 'taro: hi.'


    @@ -26,5 +26,5 @@ def say(self):


    p2 = Base(name="jiro")
    p2.add_eigen_method(say)
    p2.add_instance_method(say)
    (p1.say(), p2.say()) # --> ('taro: hi.', 'jiro: hello')
  2. yuu-ito revised this gist Dec 6, 2016. 1 changed file with 7 additions and 2 deletions.
    9 changes: 7 additions & 2 deletions dynamic_typing.py
    Original file line number Diff line number Diff line change
    @@ -7,19 +7,24 @@ def __init__(self, **kwargs):
    def add_eigen_method(self, method):
    setattr(self, method.__name__, MethodType(method, self))

    def say(self):
    return "%s: hi." % self.name

    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_eigen_method(say)
    p1.say() # --> 'taro: hi.'


    def say(self):
    return "%s: hello" % self.name


    p2 = Base(name="jiro")
    p2.add_eigen_method(say)
    (p1.say(), p2.say()) # --> ('taro: hi.', 'jiro: hello')
  3. yuu-ito revised this gist Dec 6, 2016. No changes.
  4. yuu-ito created this gist Dec 6, 2016.
    25 changes: 25 additions & 0 deletions dynamic_typing.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    # 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_eigen_method(self, method):
    setattr(self, method.__name__, MethodType(method, self))

    def say(self):
    return "%s: hi." % self.name

    p0 = Base(name="zero")
    p0.say() # --> AttributeError: 'Base' object has no attribute 'say'

    p1 = Base(name="taro")
    p1.add_eigen_method(say)
    p1.say() # --> 'taro: hi.'

    def say(self):
    return "%s: hello" % self.name

    p2 = Base(name="jiro")
    p2.add_eigen_method(say)
    (p1.say(), p2.say()) # --> ('taro: hi.', 'jiro: hello')