How to differentiate between method and function in a decorator?

前端 未结 4 1141
感情败类
感情败类 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:47

    Do you need to have the magic happen where you choose which wrapper to return, or can you defer the magic until the function is actually called? You could always try a parameter to your decorator to indicate which of the two wrappers it should use, like

    def some_decorator( clams ):
       def _mydecor(func ):
           @wraps(func)
           def wrapping(*args....)
              ...
           return wrapping
       def _myclassdecor(func):
           @wraps(func)
           .....
    
       return _mydecor if clams else _myclassdecor
    

    The other thing that I might suggest is to create a metaclass and define the init method in the metaclass to look for methods decorated with your decorator and revise them accordingly, like Alex hinted at. Use this metaclass with your base class, and since all the classes that will use the decorator will inherit from the base class, they'll also get the metaclass type and use its init as well.

提交回复
热议问题