Daneel Olivaw
Daneel Olivaw

Reputation: 2303

Getting a particular subset of methods from a Python class

I have read other posts in Stack Overflow that answer this question, but I am interested in a specific subset of methods.

Suppose you have a class Cn with n higher than 1, as well as classes C0, C1, ..., Cn-1 such that, for each i between 1 and n-1, class Ci+1 inherits from class Ci.

My question is: for any i higher than 1, how can I obtain the list of methods that belong to Ci but not to Ci-1?

Upvotes: 1

Views: 792

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121804

You can find all names defined on the class itself in the __dict__ attribute of a class; you can use the vars() function to list those more succinctly:

from types import FunctionType

for name, object in vars(Ci).items():
    if isinstance(object, FunctionType):
        print(name, 'is defined on Ci directly and not inherited')

You may need to vary the test for functions; I'm assuming here you only want plain function objects (which are bound into methods when looked up on the instance), but you may need to test for class or static methods or other callables too, depending on your use-case.

This will include names that have been re-defined; so these exist on the parent too but Ci provides a new implementation that masks that of a parent.

If you must find all names that uniquely belong to Ci and no parent provides, you'll have to filter on names that exist on the bases:

parent_defined = set().union(*(dir(b) for b in Ci.__bases__))

for name, object in vars(Ci).items():
    if name not in parent_defined and isinstance(object, FunctionType):
        print(name, 'is defined on Ci directly and not inherited')

Upvotes: 3

Related Questions