给定一个任何类型的Python对象,是否有一种简单的方法来获得该对象拥有的所有方法的列表?
或者如果这是不可能的,是否至少有一种简单的方法来检查它是否具有特定的方法,而不是在调用方法时检查是否发生错误?
给定一个任何类型的Python对象,是否有一种简单的方法来获得该对象拥有的所有方法的列表?
或者如果这是不可能的,是否至少有一种简单的方法来检查它是否具有特定的方法,而不是在调用方法时检查是否发生错误?
当前回答
...除了简单地检查调用方法时是否发生错误之外,是否至少有一种简单的方法来检查它是否具有特定的方法
虽然“请求原谅比请求允许更容易”肯定是python的方式,但你可能在寻找:
d={'foo':'bar', 'spam':'eggs'}
if 'get' in dir(d):
d.get('foo')
# OUT: 'bar'
其他回答
我已经完成了下面的函数(get_object_functions),它接收一个对象(object_)作为它的参数,并返回一个包含对象类中定义的所有方法(包括静态方法和类方法)的列表(函数):
def get_object_functions(object_):
functions = [attr_name
for attr_name in dir(object_)
if str(type(getattr(object_,
attr_name))) in ("<class 'function'>",
"<class 'method'>")]
return functions
好吧,它只是检查类的属性类型的字符串表示是否等于“<class 'function'>”或“<class 'method'>”,然后将该属性包含在函数列表中,如果那是True。
Demo
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print(f'My name is {self.name}')
@staticmethod
def say_hi():
print('hi')
@classmethod
def reproduce(cls, name):
return cls(name, 0)
person = Person('Rafael', 27)
print(get_object_functions(person))
输出
['__init__', 'introduce', 'reproduce', 'say_hi']
要获得更简洁的代码版本,请访问https://github.com/revliscano/utilities/blob/master/get_object_functions/object_functions_getter.py
我相信你想要的是这样的:
一个对象的属性列表
内置函数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']
以便在整个模块中搜索特定的方法
for method in dir(module) :
if "keyword_of_methode" in method :
print(method, end="\n")
假设我们有一个Python obj。然后查看它拥有的所有方法,包括那些被__包围的方法(魔术方法):
print(dir(obj))
要排除魔法内置,可以这样做:
[m for m in dir(obj) if not m.startswith('__')]
检查它是否有特定的方法:
hasattr(object,"method")