Python:如何从__getattr__函数中获取函数名列表?

dev*_*vtk 6 python

如何从__getattr__函数中获取类函数列表?

Python v2.7如果重要的话.

尝试使用dir内部__getattr__导致无限递归.

class Hal(object):
    def __getattr__(self, name):
        print 'I don\'t have a %s function' % name
        names = dir(self) # <-- infinite recursion happens here
        print 'My functions are: %s' % ', '.join(names)
        exit()
    def close_door(self):
        pass
x = Hal()       
x.open_door()
Run Code Online (Sandbox Code Playgroud)

这是我想要的输出:

I don't have a open_door function
My functions are: close_door, __getattr__, __init__, __doc__, ...
Run Code Online (Sandbox Code Playgroud)

获得我想要的输出的任何其他解决方案都可以正常工作.我希望在不存在函数的情况下进行模糊字符串匹配,以尝试建议用户可能具有的含义.

Mik*_*ran 2

你有什么理由不能这样做吗?

names = dir(self.__class__)
Run Code Online (Sandbox Code Playgroud)

您是否期望消费者扩展 Hal 实例以拥有自定义方法?

如果您只想要已实现的方法,而不列出内置方法,您也可以尝试以下方法:

names = [prop for prop in dir(self.__class__) if prop[1] != "_"]
Run Code Online (Sandbox Code Playgroud)