简体   繁体   English

检查方法是否在基类或派生类中定义

[英]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. 我想要一个函数来告诉我test是基类的原始版本还是派生类中实现的新版本。 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. 我发现inspect.getfullargspec也许可以解决我的问题,但不适用于我的案例所需的Python 3。

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: 默认情况下,打印的名称来自该函数的__qualname__属性:

>>> 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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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