Zack
Zack

Reputation: 1245

Check if a method is defined in the base or derived class

I want to have a function to tell me whether test is the original version from the base class or a new version implemented in the derived class. I found that inspect.getfullargspec might be able to solve my issue, but it doesn't work with Python 3 which is needed for my case.

class base_class(object):
    @staticmethod 
    def test(a, b, c):
        pass

class child_class(base_class):
    @staticmethod
    def test(a, b):
        pass 

class child_class_2(base_class):
    pass

Upvotes: 0

Views: 1180

Answers (1)

Mad Physicist
Mad Physicist

Reputation: 114578

You don't need any fancy inspection to do this:

>>> x = child_class_2()                                                     
>>> x.test                                                                  
<function base_class.test at 0x7fea1a07f7b8>

>>> y = child_class()                                                       
>>> y.test                                                                  
<function child_class.test at 0x7fea1a07f950>

The printed name comes from the __qualname__ attribute of the function by default:

>>> x.test.__qualname__
base_class.test
>>> y.test.__qualname__
child_class.test

A hacky way to get the name of the class is

x.test.__qualname__[:-len(x.test.__name__) - 1]

Upvotes: 4

Related Questions