【问题标题】:Checking the type of a method generator检查方法生成器的类型
【发布时间】: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


【解决方案1】:

调用你的函数:

c = MyClass() 
my_func(c.other_func([1,2,3])) 

完整代码:

import types

def my_func(other_func):
    if isinstance(other_func, types.GeneratorType):
        # do something
        print ("test1")
    elif isinstance(other_func, types.FunctionType):
        # do something else
        print("test2")
    else:
        raise TypeError(f"other_func is of type {type(other_func)} which is not supported")


class MyClass:
    def other_func(self, items):
        for item in items:
            yield item

c = MyClass() // <------
my_func(c.other_func([1,2,3])) // <------

【讨论】:

  • 感谢调用函数的建议。这不是我的代码的正确答案,但它让我在正确的轨道上自己找到它。 +1
  • 我很高兴能帮上忙! :) @berkelem
【解决方案2】:

这样做的方法是使用.__func__隐藏属性如下:

import types

def my_func(other_func):
    if isinstance(other_func.__func__(other_func.__self__), types.GeneratorType):
        # do something
    elif isinstance(other_func.__func__(other_func.__self__), types.FunctionType):
        # do something else
    else:
        raise TypeError(f"other_func is of type {type(other_func)} which is not supported")

这更深入地挖掘了函数,而不是仅仅说它是一个类方法。

【讨论】:

    猜你喜欢
    • 2017-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-14
    • 2011-03-16
    • 1970-01-01
    • 1970-01-01
    • 2014-01-07
    相关资源
    最近更新 更多