【问题标题】:inspect.ismethod() returns false for the instance method in the decoratorinspect.ismethod() 为装饰器中的实例方法返回 false
【发布时间】:2018-06-15 20:51:06
【问题描述】:

我正在尝试使用inspect.ismethod() 检测函数是实例方法还是python 装饰器中的模块级函数。它为此返回 false。是什么原因?如何检测函数是实例方法还是装饰器内部的模块级函数,如下所示。

例子:

import inspect
class A(object):
  @deco("somearg")
  def sample(self):
      print "abc"

a = A()
print inspect.ismethod(a.sample) # Returns True

上面的打印返回true。

我的装饰器如下所示。我需要在实际代码中将参数传递给装饰器,使其位于函数内部:

def deco(some_arg=None):
    def decorator(func):
        def wrapper(*args, **kwargs):
            print some_arg
            print inspect.ismethod(func)
        return wrapper
    return decorator

inspect.ismmethod() 上面返回 false。

我的python版本是2.7.13

【问题讨论】:

  • 那是因为你的wrapper 函数变成了这里的方法,当类结束时。它包装的函数仍然是一个函数。没有办法知道你想知道什么。

标签: python python-decorators


【解决方案1】:

注意从函数对象到 (unbound or bound) 方法对象在每次检索属性时发生 类或实例。

你正在装饰的是一个函数。嵌套在类中的函数仍然是函数。当您从类或类的实例访问函数时,它被归类为方法。

您可以改为从wrapper 中的self 参数访问方法对象:

def deco(some_arg=None):
    def decorator(func):
        def wrapper(*args, **kwargs):
            print some_arg
            print inspect.ismethod(args[0].sample) 
        return wrapper
    return decorator

【讨论】:

    猜你喜欢
    • 2019-01-03
    • 2019-02-03
    • 2013-02-12
    • 1970-01-01
    相关资源
    最近更新 更多