Skip to content

Instantly share code, notes, and snippets.

@alex-moon
Created August 13, 2015 09:16
Show Gist options
  • Save alex-moon/914c07e337d5443a295b to your computer and use it in GitHub Desktop.
Save alex-moon/914c07e337d5443a295b to your computer and use it in GitHub Desktop.
Find Inherited Methods on a class in Python
#!/usr/bin/python
import inspect
class SuperSuperClass(object):
def super_super_method(self):
return 'super super method'
class SuperClass(SuperSuperClass):
def super_method(self):
return 'super method'
class SubClass(SuperClass):
def sub_method(self):
return 'sub method'
class ExampleClass(SubClass):
def super_super_method(self):
return 'overridden method'
def example_method(self):
return 'defined method'
def get_inherited_class(klass, method_name):
for superclass in klass.__bases__:
next_superclass = get_inherited_class(superclass, method_name)
if next_superclass is not None:
return next_superclass
for supermethod_name, supermethod in inspect.getmembers(superclass, inspect.ismethod):
if supermethod_name == method_name:
return superclass
return None
def annotate_methods(klass):
annotated_methods = []
for method_name, method in inspect.getmembers(klass, inspect.ismethod):
annotated_method = {
'method_name': method_name,
'method': method,
'method_mode': 'unknown'
}
for superclass in klass.__bases__:
for annotated_supermethod in annotate_methods(superclass):
if method_name == annotated_supermethod['method_name']:
# the method is inherited or overridden - but from where?
inherited_class = get_inherited_class(klass, method_name)
if method == annotated_supermethod['method']:
annotated_method['method_mode'] = 'inherited from %s' % inherited_class.__name__
else:
annotated_method['method_mode'] = 'overridden from %s' % inherited_class.__name__
if annotated_method['method_mode'] == 'unknown':
annotated_method['method_mode'] = 'defined in %s' % klass.__name__
annotated_methods.append(annotated_method)
return annotated_methods
for example_method in annotate_methods(ExampleClass):
print "The method %s in ExampleClass is %s" % (example_method['method_name'], example_method['method_mode'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment