Last active
August 11, 2016 03:35
-
-
Save adi-li/e3e9fa608157f49697f8e3157c0d57f7 to your computer and use it in GitHub Desktop.
Try to extend a class by adding / overriding original method in 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
class Foo(object): | |
def bar(self): | |
return 'bar' | |
def new_bar(self, super_method): | |
if super_method is not None: | |
return ', '.join([super_method(), 'new_bar']) | |
return 'new_bar' | |
def extend(cls, method_name, method): | |
super_method = getattr(cls, method_name, None) | |
def new_method(self, *args, **kwargs): | |
if super_method is not None: | |
bounded_super = super_method.__get__(self, cls) | |
return method(self, bounded_super, *args, **kwargs) | |
setattr(cls, method_name, new_method) | |
old_foo = Foo() | |
old_foo.bar() # 'bar' | |
extend(Foo, 'bar', new_bar) | |
new_foo = Foo() | |
new_foo.bar() # 'bar, new_bar' | |
old_foo.bar() # 'bar, new_bar' | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment