给定一个任何类型的Python对象,是否有一种简单的方法来获得该对象拥有的所有方法的列表?
或者如果这是不可能的,是否至少有一种简单的方法来检查它是否具有特定的方法,而不是在调用方法时检查是否发生错误?
给定一个任何类型的Python对象,是否有一种简单的方法来获得该对象拥有的所有方法的列表?
或者如果这是不可能的,是否至少有一种简单的方法来检查它是否具有特定的方法,而不是在调用方法时检查是否发生错误?
当前回答
这里指出的所有方法的问题是,您不能确定某个方法不存在。
在Python中,您可以通过__getattr__和__getattribute__拦截点调用,从而可以在“运行时”创建方法。
例子:
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中使用“请求原谅比请求许可更容易”的范例。
其他回答
我相信你想要的是这样的:
一个对象的属性列表
内置函数dir()可以完成这项工作。
摘自Python shell的help(dir)输出:
dir(...) dir([object]) -> list of strings If called without an argument, return the names in the current scope. Else, return an alphabetized list of names comprising (some of) the attributes of the given object, and of attributes reachable from it. If the object supplies a method named __dir__, it will be used; otherwise the default dir() logic is used and returns: for a module object: the module's attributes. for a class object: its attributes, and recursively the attributes of its bases. for any other object: its attributes, its class's attributes, and recursively the attributes of its class's base classes.
例如:
$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = "I am a string"
>>>
>>> type(a)
<class 'str'>
>>>
>>> dir(a)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__',
'__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__',
'__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__',
'__setattr__', '__sizeof__', '__str__', '__subclasshook__',
'_formatter_field_name_split', '_formatter_parser', 'capitalize',
'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find',
'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace',
'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition',
'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip',
'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title',
'translate', 'upper', 'zfill']
如果你特别需要方法,你应该使用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)。
打开Bash shell (Ubuntu上使用Ctrl + Alt + T)。在其中启动Python 3 shell。创建一个对象来观察的方法。只需要在后面加一个点,然后按Tab键两次,你就会看到如下内容:
user@note:~$ python3
Python 3.4.3 (default, Nov 17 2016, 01:08:31)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import readline
>>> readline.parse_and_bind("tab: complete")
>>> s = "Any object. Now it's a string"
>>> s. # here tab should be pressed twice
s.__add__( s.__rmod__( s.istitle(
s.__class__( s.__rmul__( s.isupper(
s.__contains__( s.__setattr__( s.join(
s.__delattr__( s.__sizeof__( s.ljust(
s.__dir__( s.__str__( s.lower(
s.__doc__ s.__subclasshook__( s.lstrip(
s.__eq__( s.capitalize( s.maketrans(
s.__format__( s.casefold( s.partition(
s.__ge__( s.center( s.replace(
s.__getattribute__( s.count( s.rfind(
s.__getitem__( s.encode( s.rindex(
s.__getnewargs__( s.endswith( s.rjust(
s.__gt__( s.expandtabs( s.rpartition(
s.__hash__( s.find( s.rsplit(
s.__init__( s.format( s.rstrip(
s.__iter__( s.format_map( s.split(
s.__le__( s.index( s.splitlines(
s.__len__( s.isalnum( s.startswith(
s.__lt__( s.isalpha( s.strip(
s.__mod__( s.isdecimal( s.swapcase(
s.__mul__( s.isdigit( s.title(
s.__ne__( s.isidentifier( s.translate(
s.__new__( s.islower( s.upper(
s.__reduce__( s.isnumeric( s.zfill(
s.__reduce_ex__( s.isprintable(
s.__repr__( s.isspace(
...除了简单地检查调用方法时是否发生错误之外,是否至少有一种简单的方法来检查它是否具有特定的方法
虽然“请求原谅比请求允许更容易”肯定是python的方式,但你可能在寻找:
d={'foo':'bar', 'spam':'eggs'}
if 'get' in dir(d):
d.get('foo')
# OUT: 'bar'
您可以使用内置的dir()函数来获得模块的所有属性的列表。在命令行上尝试一下,看看它是如何工作的。
>>> import moduleName
>>> dir(moduleName)
另外,您可以使用hasattr(module_name, "attr_name")函数来确定模块是否具有特定的属性。
有关更多信息,请参阅Python自省。