How to differentiate between method and function in a decorator?

前端 未结 4 1075
感情败类
感情败类 2021-02-06 02:38

I want to write a decorator that acts differently depending on whether it is applied to a function or to a method.

def some_decorator(func):
    if the_magic_hap         


        
4条回答
  •  温柔的废话
    2021-02-06 02:50

    From Python 3.3 onwards by using PEP 3155:

    def some_decorator(func):
        if func.__name__ != func.__qualname__:
            print 'Yay, found a method ^_^ (unbound jet)'
        else:
            print 'Meh, just an ordinary function :/'
        return func
    

    A method x of class A will have a __qualname__ that is A.x while a function x will have a __qualname__ of x.

提交回复
热议问题