给定一个任何类型的Python对象,是否有一种简单的方法来获得该对象拥有的所有方法的列表?
或者如果这是不可能的,是否至少有一种简单的方法来检查它是否具有特定的方法,而不是在调用方法时检查是否发生错误?
给定一个任何类型的Python对象,是否有一种简单的方法来获得该对象拥有的所有方法的列表?
或者如果这是不可能的,是否至少有一种简单的方法来检查它是否具有特定的方法,而不是在调用方法时检查是否发生错误?
当前回答
例如,如果你正在使用shell plus,你可以用这个代替:
>> MyObject??
这样,带'??’就在你的对象后面,它会显示类的所有属性/方法。
其他回答
这里指出的所有方法的问题是,您不能确定某个方法不存在。
在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中使用“请求原谅比请求许可更容易”的范例。
假设我们有一个Python obj。然后查看它拥有的所有方法,包括那些被__包围的方法(魔术方法):
print(dir(obj))
要排除魔法内置,可以这样做:
[m for m in dir(obj) if not m.startswith('__')]
获取任何对象的方法列表的最简单方法是使用help()命令。
help(object)
它将列出与该对象相关的所有可用/重要方法。
例如:
help(str)
我已经完成了下面的函数(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
打开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(