wtayyeb
wtayyeb

Reputation: 1959

How to find methods which are only defined in a subclass, in Python 2.7?

Is there a clean way to get methods only defined in a subclass that not defined in parent class?

class Parent(object):
     def method_of_parent(self):
         pass
class SubClass(Parent):
     def method_of_subclass(self):
         pass

# desired:
>>> print(get_subclass_methods(SubClass))
['method_of_subclass',]

Upvotes: 7

Views: 1621

Answers (2)

Tomerikoo
Tomerikoo

Reputation: 19422

You can achieve that using a few ingredients:

class Parent(object):
     def method_of_parent(self):
         pass
class SubClass(Parent):
     def method_of_subclass(self):
         pass

def get_subclass_methods(cls):
    methods = set(dir(cls()))
    unique_methods = methods.difference(*(dir(base()) for base in cls.__bases__))
    return list(unique_methods)

print(get_subclass_methods(SubClass))

Gives:

['method_of_subclass']

This also supports multiple inheritance so also doing:

class SubSubClass(SubClass):
    def method_of_subsubclass(self):
        pass

print(get_subclass_methods(SubSubClass))

Will give:

['method_of_subsubclass']

Upvotes: 3

Kenji Noguchi
Kenji Noguchi

Reputation: 1773

I think there are many corner cases but here is one of solutions.

import inspect


class Parent(object):
     def method_of_parent(self):
         pass
class SubClass(Parent):
     def method_of_subclass(self):
         pass

def get_subclass_methods(child_cls):
    parents = inspect.getmro(child_cls)[1:]
    parents_methods = set()
    for parent in parents:
        members = inspect.getmembers(parent, predicate=inspect.ismethod)
        parents_methods.update(members)

    child_methods = set(inspect.getmembers(child_cls, predicate=inspect.ismethod))

    child_only_methods = child_methods - parents_methods
    return [m[0] for m in child_only_methods]

print(get_subclass_methods(SubClass))

Result

['method_of_subclass']

Upvotes: 3

Related Questions