I looked at the following posts and blogs which explain to do this with a function. I wonder if its even legal to do the same for a class or object method? Will appreciate answers which work for Python2 (though its good to know how it works for Python3 as well).
Sources from stackoverflow:
Override module method where from...import is used and Override a method at instance level
blogs with similar content:
https://tryolabs.com/blog/2013/07/05/run-time-method-patching-python/ http://igorsobreira.com/2011/02/06/adding-methods-dynamically-in-python.html
This code illustrates my intention and what I tried:
class Person:
def __init__(self, name):
self.name = name
class OtherPerson:
def __init__(self, name):
self.name = name
def do_something(self):
print self.name + '$$'
p = Person('alpha')
p.do_something = OtherPerson.do_something
# TypeError: unbound method do_something() must be called with
OtherPerson #instance as first argument (got nothing instead)
p.do_something()
op = OtherPerson('beta')
p.do_something = op.do_something
# output: 'beta$$' I would like to get 'alpha$$'
p.do_something()
Tried following suggestion from @khelwood:
Person.do_something = OtherPerson.do_something
#TypeError: unbound method do_something() must be called with OtherPerson instance as first argument (got nothing instead)
# Works if OtherPerson.do_something is staticmethod
p.do_something()