仅获取类的声明方法(不包括继承类的方法)

时间:2017-11-09 11:00:04

标签: python inheritance

我在Python 3.5中遇到了问题。我有一个继承自另一个(A)的类(B)。我正在尝试只获取B中声明的方法,但它返回B类中声明的方法,并且还继承了A类中的方法。

这里是代码:

class A:

    def a_method_1(self):
        """ WILL BE OVERRIDEN """
        return True

    def a_method_2(self):
        """ WON'T BE OVERRIDEN """
        return True


class B(A):

    def b_method_1(self):
        """ NOT OVERRIDEN """
        return True

    def get_methods(self):
        """ 
           NOT OVERRIDEN 
           This function filters special python methods. 
        """

        methods = [method for method in dir(self) if callable(getattr(self, method))
                      and not method[:2] == '__']
        return methods

    def a_method_1(self):
        """ OVERRIDEN """
        return True


if __name__ == "__main__":
    B_obj = B()
    print(B_obj.get_methods())

返回:

>>> ['a_method_1', 'a_method_2', 'b_method_1', 'get_methods']

我想要:

>>> ['a_method_1', 'b_method_1', 'get_methods']

如何修改get_methods以过滤继承的方法?

祝你有个美好的一天, 谢谢。

1 个答案:

答案 0 :(得分:1)

使用vars

>>> vars(B)
mappingproxy({'__doc__': None,
              '__module__': '__main__',
              'a_method_1': <function __main__.B.a_method_1>,
              'b_method_1': <function __main__.B.b_method_1>,
              'get_methods': <function __main__.B.get_methods>})


>>> import inspect
>>> [name for name, attr in vars(B).items() if inspect.isfunction(attr)]
['b_method_1', 'get_methods', 'a_method_1']
相关问题