查找Python对象具备的方法

给定任何种类的Python对象,是否有一种简单的方法来获取该对象具备的全部方法的列表? html

要么, python

若是这不可能,那么除了简单地检查调用该方法时是否发生错误以外,是否至少有一种简单的方法来检查它是否具备特定的方法? app


#1楼

...至少有一种简单的方法能够检查它是否具备特定的方法,而不单单是在调用该方法时检查是否发生错误 ssh

尽管“ 比请求更容易得到宽恕 ”无疑是Python方式,但您正在寻找的多是: 函数

d={'foo':'bar', 'spam':'eggs'}
if 'get' in dir(d):
    d.get('foo')
# OUT: 'bar'

#2楼

最简单的方法是使用dir(objectname) 。 它将显示该对象可用的全部方法。 很棒的把戏。 spa


#3楼

此处指出的全部方法的问题在于,您不能肯定某个方法不存在。 code

在Python中,您能够经过__getattr____getattribute__截取点,从而能够在“运行时”建立方法 orm

范例: htm

class MoreMethod(object):
    def some_method(self, x):
        return x
    def __getattr__(self, *args):
        return lambda x: x*2

若是执行它,则能够调用对象字典中不存在的方法... 对象

>>> o = MoreMethod()
>>> o.some_method(5)
5
>>> dir(o)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattr__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'some_method']
>>> o.i_dont_care_of_the_name(5)
10

这就是为何您在Python中使用Easier而不是权限范式来请求宽恕


#4楼

若是您特别想要方法 ,则应使用inspect.ismethod

对于方法名称:

import inspect
method_names = [attr for attr in dir(self) if inspect.ismethod(getattr(self, attr))]

对于方法自己:

import inspect
methods = [member for member in [getattr(self, attr) for attr in dir(self)] if inspect.ismethod(member)]

有时inspect.isroutine也可能有用(对于内置程序,C扩展,不具备“绑定”编译器指令的Cython)。


#5楼

能够建立一个getAttrs函数,该函数将返回对象的可调用属性名称

def getAttrs(object):
  return filter(lambda m: callable(getattr(object, m)), dir(object))

print getAttrs('Foo bar'.split(' '))

那会回来

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__',
 '__delslice__', '__eq__', '__format__', '__ge__', '__getattribute__', 
 '__getitem__', '__getslice__', '__gt__', '__iadd__', '__imul__', '__init__', 
 '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', 
 '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', 
 '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', 
 '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 
 'remove', 'reverse', 'sort']
相关文章
相关标签/搜索