Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/336.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 仅获取类的声明方法(不包括继承的类和方法)_Python_Inheritance - Fatal编程技术网

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

Python 仅获取类的声明方法(不包括继承的类和方法),python,inheritance,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

我在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\u方法以过滤继承的方法?

祝你过得愉快, 谢谢。

使用:

>变量(B)
mappingproxy({''文档]:无,
“\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu,
“a_方法_1”:,
“b_方法_1”:,
“获取方法”:})
>>>进口检验
>>>[如果inspect.isfunction(attr)为name,则名称为attr,在vars(B).items()中为attr]
['b_方法1'、'get_方法'、'a_方法1']

您是只想过滤列表comphrension,还是想从类中完全删除任何不需要的继承方法?@Reti43我想过滤列表理解。如果您想从类实例中过滤相同的方法,
vars(B_obj.\u class_uuuuuuu)将实现相同的效果。或者
self.\uu class\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu。
>>> 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']