简体   繁体   English

如何获取用户定义的方法名称?

[英]How to get user-defined methods name?

I'm trying to get all the user-defined methods name from a class, ex:我正在尝试从 class 获取所有用户定义的方法名称,例如:

class MyClass:
    def __init__(self, param1, param2):
        pass

    def one_method(self):
        pass

    def __repr__(self):
        pass

    def __str__(self):
        pass

    def __my_method_no_2(self, param2):
        pass

    def _my_method_no_3(self):
        pass

so far I have come to the following approach:到目前为止,我已经采用以下方法:

import inspect 

[name for name, _ in inspect.getmembers(MyClass, inspect.isroutine)
 if name not in {'__init_subclass__', '__subclasshook__'} and 
 getattr(MyClass, name).__qualname__.startswith(MyClass.__name__)]

output: output:

['_MyClass__my_method_no_2',
 '__init__',
 '__repr__',
 '__str__',
 '_my_method_no_3',
 'one_method']

this is the expected output, but this looks "ugly" and not even sure if is the right approach这是预期的 output,但这看起来“丑陋”,甚至不确定是否是正确的方法

In Python 3.x , you can use dir without inspect or any external libraries:Python 3.x中,您可以使用dir而无需 检查或任何外部库:

method_list = [func for func in dir(Foo) if callable(getattr(Foo, func))]

To handle every method that you newly define in your class and override in your class, Try this:要处理您在 class 中新定义并在 class 中覆盖的每个方法,试试这个:

class MyClass:
    li = []
    def __init__(self, param1, param2):
        pass

    def one_method(self):
        pass

    def __repr__(self):
        pass

    def __str__(self):
        pass

    def __my_method_no_2(self, param2):
        pass

    def _my_method_no_3(self):
        pass


print([func for func in dir(MyClass) if callable(getattr(MyClass, func)) and func in MyClass.__dict__])

Outputs:输出:

['_MyClass__my_method_no_2', '__init__', '__repr__', '__str__', '_my_method_no_3', 'one_method']


Got the idea from here , but using __dict__ instead of dir .这里得到想法,但使用__dict__而不是dir

Every python objects has a __dict__ attribute containing names of all attributes.每个 python 对象都有一个__dict__属性,其中包含所有属性的名称。 Relevant docshere相关文档在这里

The idea is: get a list of attributes from __dict__ and filter out everything non-callable这个想法是:从__dict__获取属性列表并过滤掉所有不可调用的内容

[attr for attr in  MyClass.__dict__ if callable(getattr(MyClass, attr))]

Matches with your output与您的 output 匹配

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

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