我想通过类中的方法进行迭代,或者根据目前的方法不同地处理类或实例对象。我如何获得类方法的列表?
还看到:
方法中的方法如何列出 Python 2.5模块? 循环在 Python / IronPython对象 方法 找到方法 对象有 我怎么看里面 Python对象? 我该怎么做 中对对象进行内省 Python 2. x ? 如何获得 对象的方法和的完整列表 属性? 找出 函数可以从类中获得 实例在python中?
我想通过类中的方法进行迭代,或者根据目前的方法不同地处理类或实例对象。我如何获得类方法的列表?
还看到:
方法中的方法如何列出 Python 2.5模块? 循环在 Python / IronPython对象 方法 找到方法 对象有 我怎么看里面 Python对象? 我该怎么做 中对对象进行内省 Python 2. x ? 如何获得 对象的方法和的完整列表 属性? 找出 函数可以从类中获得 实例在python中?
当前回答
假设您想知道与list类关联的所有方法 只需输入以下内容
print (dir(list))
上面给出了list类的所有方法
其他回答
使用检查。Ismethod, dir和getattr
import inspect
class ClassWithMethods:
def method1(self):
print('method1')
def method2(self):
print('method2')
obj=ClassWithMethods()
method_names = [attr for attr in dir(obj) if inspect.ismethod(getattr(obj,attr))
print(method_names)
输出:
[[('method1', <bound method ClassWithMethods.method1 of <__main__.ClassWithMethods object at 0x00000266779AF388>>), ('method2', <bound method ClassWithMethods.method2 of <__main__.ClassWithMethods object at 0x00000266779AF388>>)]]
Python 3。X答案没有外部库
method_list = [func for func in dir(Foo) if callable(getattr(Foo, func))]
dunder-excluded结果:
method_list = [func for func in dir(Foo) if callable(getattr(Foo, func)) and not func.startswith("__")]
如果你只想列出一个python类的方法
import numpy as np
print(np.random.__all__)
要生成一个方法列表,请将方法名称放在一个列表中,不使用通常的括号。删除名称并附加圆括号,这将调用该方法。
def methodA():
print("@ MethodA")
def methodB():
print("@ methodB")
a = []
a.append(methodA)
a.append(methodB)
for item in a:
item()
如果你的方法是“常规”方法,而不是静态方法、类方法等。 我想出了一个小窍门
for k, v in your_class.__dict__.items():
if "function" in str(v):
print(k)
这可以通过相应改变if条件中的“function”扩展到其他类型的方法。 在Python 2.7和Python 3.5中测试。