Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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',]
like image 283
wtayyeb Avatar asked Oct 12 '16 20:10

wtayyeb


People also ask

How do I get list of methods in a Python class?

To list the methods for this class, one approach is to use the dir() function in Python. The dir() function will return all functions and properties of the class.

How do you access subclasses in Python?

If you do have a string representing the name of a class and you want to find that class's subclasses, then there are two steps: find the class given its name, and then find the subclasses with __subclasses__ as above. However you find the class, cls. __subclasses__() would then return a list of its subclasses.

What is __ Init_subclass __ in Python?

The __init_subclass__ class method is called when the class itself is being constructed. It gets passed the cls and can make modifications to it. Here's the pattern I used: class AsyncInject: def __init_subclass__(cls, **kwargs): super().

How do you check if an object is a subclass Python?

Python issubclass() is built-in function used to check if a class is a subclass of another class or not. This function returns True if the given class is the subclass of given class else it returns False. Parameters: Object: class to be checked.


1 Answers

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']
like image 163
Kenji Noguchi Avatar answered Sep 23 '22 16:09

Kenji Noguchi