给定一个任何类型的Python对象,是否有一种简单的方法来获得该对象拥有的所有方法的列表?
或者如果这是不可能的,是否至少有一种简单的方法来检查它是否具有特定的方法,而不是在调用方法时检查是否发生错误?
给定一个任何类型的Python对象,是否有一种简单的方法来获得该对象拥有的所有方法的列表?
或者如果这是不可能的,是否至少有一种简单的方法来检查它是否具有特定的方法,而不是在调用方法时检查是否发生错误?
当前回答
最简单的方法是使用dir(objectname)。它将显示该对象的所有可用方法。
其他回答
我已经完成了下面的函数(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
检查它是否有特定的方法:
hasattr(object,"method")
以便在整个模块中搜索特定的方法
for method in dir(module) :
if "keyword_of_methode" in method :
print(method, end="\n")
打开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(
例如,如果你正在使用shell plus,你可以用这个代替:
>> MyObject??
这样,带'??’就在你的对象后面,它会显示类的所有属性/方法。