给定一个任何类型的Python对象,是否有一种简单的方法来获得该对象拥有的所有方法的列表?
或者如果这是不可能的,是否至少有一种简单的方法来检查它是否具有特定的方法,而不是在调用方法时检查是否发生错误?
给定一个任何类型的Python对象,是否有一种简单的方法来获得该对象拥有的所有方法的列表?
或者如果这是不可能的,是否至少有一种简单的方法来检查它是否具有特定的方法,而不是在调用方法时检查是否发生错误?
当前回答
这里有一个很好的一行代码(但也会得到属性):
print(*dir(obj), sep='\n')
其他回答
如果你特别需要方法,你应该使用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)]
有时检查。isroutine也很有用(对于内置,C扩展,没有“binding”编译器指令的Cython)。
可以创建一个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']
例如,如果你正在使用shell plus,你可以用这个代替:
>> MyObject??
这样,带'??’就在你的对象后面,它会显示类的所有属性/方法。
大多数时候,我想看到用户定义的方法,我不想看到以'__'开头的内置属性,如果你想,你可以使用以下代码:
object_methods = [method_name for method_name in dir(object) if callable(getattr(object, method_name)) and '__' not in method_name]
例如,对于这个类:
class Person:
def __init__(self, name):
self.name = name
def print_name(self):
print(self.name)
上面的代码将输出:['print_name']
...除了简单地检查调用方法时是否发生错误之外,是否至少有一种简单的方法来检查它是否具有特定的方法
虽然“请求原谅比请求允许更容易”肯定是python的方式,但你可能在寻找:
d={'foo':'bar', 'spam':'eggs'}
if 'get' in dir(d):
d.get('foo')
# OUT: 'bar'