Skip to content

Instantly share code, notes, and snippets.

@adi-li
Last active August 11, 2016 03:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adi-li/e3e9fa608157f49697f8e3157c0d57f7 to your computer and use it in GitHub Desktop.
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
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