Created
October 11, 2012 18:32
-
-
Save kmerenkov/3874555 to your computer and use it in GitHub Desktop.
Way to call a method on all parents
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
# -*- 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