我想通过类中的方法进行迭代,或者根据目前的方法不同地处理类或实例对象。我如何获得类方法的列表?
还看到:
方法中的方法如何列出 Python 2.5模块? 循环在 Python / IronPython对象 方法 找到方法 对象有 我怎么看里面 Python对象? 我该怎么做 中对对象进行内省 Python 2. x ? 如何获得 对象的方法和的完整列表 属性? 找出 函数可以从类中获得 实例在python中?
我想通过类中的方法进行迭代,或者根据目前的方法不同地处理类或实例对象。我如何获得类方法的列表?
还看到:
方法中的方法如何列出 Python 2.5模块? 循环在 Python / IronPython对象 方法 找到方法 对象有 我怎么看里面 Python对象? 我该怎么做 中对对象进行内省 Python 2. x ? 如何获得 对象的方法和的完整列表 属性? 找出 函数可以从类中获得 实例在python中?
当前回答
试一试 print(帮助(名称)) 它输出类的方法
其他回答
这也是可行的:
在mymodule.py:
def foo(x):
return 'foo'
def bar():
return 'bar'
在另一个文件中:
import inspect
import mymodule
method_list = [ func[0] for func in inspect.getmembers(mymodule, predicate=inspect.isroutine) if callable(getattr(mymodule, func[0])) ]
输出:
(“foo”、“酒吧”)
来自Python文档:
inspect.isroutine(object)
如果对象是用户定义的或内置的函数或方法,则返回true。
For my use case, I needed to distinguish between class methods, static methods, properties, and instance methods. The inspect module confuses the issue a bit (particularly with class methods and instance methods), so I used vars based on a comment on this SO question. The basic gist is to use vars to get the __dict__ attribute of the class, then filter based on various isinstance checks. For instance methods, I check that it is callable and not a class method. One caveat: this approach of using vars (or __dict__ for that matter) won't work with __slots__. Using Python 3.6.9 (because it's what the Docker image I'm using as my interpreter has):
class MethodAnalyzer:
class_under_test = None
@classmethod
def get_static_methods(cls):
if cls.class_under_test:
return {
k for k, v in vars(cls.class_under_test).items()
if isinstance(v, staticmethod)
}
return {}
@classmethod
def get_class_methods(cls):
if cls.class_under_test:
return {
k for k, v in vars(cls.class_under_test).items()
if isinstance(v, classmethod)
}
return {}
@classmethod
def get_instance_methods(cls):
if cls.class_under_test:
return {
k for k, v in vars(cls.class_under_test).items()
if callable(v) and not isinstance(v, classmethod)
}
return {}
@classmethod
def get_properties(cls):
if cls.class_under_test:
return {
k for k, v in vars(cls.class_under_test).items()
if isinstance(v, property)
}
return {}
为了查看它的运行情况,我创建了这个小测试类:
class Foo:
@staticmethod
def bar(baz):
print(baz)
@property
def bleep(self):
return 'bloop'
@classmethod
def bork(cls):
return cls.__name__
def flank(self):
return 'on your six'
那时:
MethodAnalyzer.class_under_test = Foo
print(MethodAnalyzer.get_instance_methods())
print(MethodAnalyzer.get_class_methods())
print(MethodAnalyzer.get_static_methods())
print(MethodAnalyzer.get_properties())
的输出
{'flank'}
{'bork'}
{'bar'}
{'bleep'}
在这个例子中,我放弃了实际的方法,但如果你需要保留它们,你可以使用字典理解式而不是集合理解式:
{
k, v for k, v in vars(cls.class_under_test).items()
if callable(v) and not isinstance(v, classmethod)
}
就像这样
pprint.pprint([x for x in dir(list) if not x.startswith("_")])
你也可以从types中导入FunctionType并使用类测试它。__dict__:
from types import FunctionType
class Foo:
def bar(self): pass
def baz(self): pass
def methods(cls):
return [x for x, y in cls.__dict__.items() if type(y) == FunctionType]
methods(Foo) # ['bar', 'baz']
要生成一个方法列表,请将方法名称放在一个列表中,不使用通常的括号。删除名称并附加圆括号,这将调用该方法。
def methodA():
print("@ MethodA")
def methodB():
print("@ methodB")
a = []
a.append(methodA)
a.append(methodB)
for item in a:
item()