【发布时间】:2019-07-01 09:46:05
【问题描述】:
我有一个函数,它接受另一个函数作为参数。我希望它检查参数是常规函数还是生成器。
import types
def my_func(other_func):
if isinstance(other_func, types.GeneratorType):
# do something
elif isinstance(other_func, types.FunctionType):
# do something else
else:
raise TypeError(f"other_func is of type {type(other_func)} which is not supported")
但问题是该函数是一个类方法,所以我得到以下内容:
other_func is of type <class 'method'> which is not supported
类方法是这样的
MyClass:
def other_func(self, items):
for item in items:
yield item
有什么方法可以检查类方法是生成器还是函数?
【问题讨论】:
-
用不同类型的函数做不同的事情的用例是什么?
-
你如何调用你的函数 my_func
-
我将它用作 MPI 分布式任务的通用函数调用管理器。
-
你应该检查函数的结果而不是函数本身。
标签: python python-3.x types generator