【问题标题】:How to indentify if a function being decorated is a function or a method? [duplicate]如何识别被修饰的函数是函数还是方法? [复制]
【发布时间】:2013-09-07 17:36:02
【问题描述】:

如何识别当前被修饰的函数是方法(属于类)还是函数?

class ClassA:
  @mydecorator
    def method(self)
    pass

  @staticmethod

@mydecorator
def function()
  pass

mydecorator 需要知道被装饰的函数是:

  • 一种方法 (is_method)
  • 静态方法 (is_static)
  • 类方法 (is_classmethod)
  • 一个全局函数 (is_function)

我们怎样才能做到这一点?

谢谢!

【问题讨论】:

  • 应用装饰器时,函数还是函数;该方法仅在从类访问时才被绑定(每次都是动态的)。

标签: python static


【解决方案1】:
is_method = lambda f: hasattr(f, 'im_self')

is_static = lambda f: isinstance(f, types.FunctionType)

is_classmethod = lambda f: getattr(f, 'im_self', None) is not None

is_function = lambda f: not hasattr(f, 'im_self')

http://docs.python.org/2/reference/datamodel.html#types

【讨论】:

  • 这对方法上的实例不起作用(f 应该等于 ClassA.method 但这里我们有 ClassA().method())
猜你喜欢
  • 2020-11-22
  • 1970-01-01
  • 1970-01-01
  • 2021-10-05
  • 2012-02-22
  • 1970-01-01
  • 2015-05-23
  • 2015-06-15
  • 2012-03-24
相关资源
最近更新 更多