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',]
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.
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.
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().
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.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With