Skip to content

Instantly share code, notes, and snippets.

@kmerenkov
Created October 11, 2012 18:32
Show Gist options
  • Save kmerenkov/3874555 to your computer and use it in GitHub Desktop.
Save kmerenkov/3874555 to your computer and use it in GitHub Desktop.
Way to call a method on all parents
# -*- coding: utf-8 -*-
def maybe_call_super(cls, instance, method):
next_mro_obj = super(cls, instance)
method = getattr(next_mro_obj, method, None)
if method:
method()
class A(object):
def foo(self):
maybe_call_super(A, self, 'foo')
print 'A.foo'
class B(object):
def foo(self):
maybe_call_super(B, self, 'foo')
print 'B.foo'
class C(A, B):
def foo(self):
maybe_call_super(C, self, 'foo')
print 'C.foo'
# In [1]: from foo import C
#
# In [2]: C().foo()
# B.foo
# A.foo
# C.foo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment