简体   繁体   中英

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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM