Using the same decorator (with arguments) with functions and methods

后端 未结 5 1521
隐瞒了意图╮
隐瞒了意图╮ 2020-12-05 00:54

I have been trying to create a decorator that can be used with both functions and methods in python. This on it\'s own is not that hard, but when creating a decorator that

5条回答
  •  一向
    一向 (楼主)
    2020-12-05 01:35

    The decorator is always applied to a function object -- have the decorator print the type of its argument and you'll be able to confirm that; and it should generally return a function object, too (which is already a decorator with the proper __get__!-) although there are exceptions to the latter.

    I.e, in the code:

    class X(object):
    
      @deco
      def f(self): pass
    

    deco(f) is called within the class body, and, while you're still there, f is a function, not an instance of a method type. (The method is manufactured and returned in f's __get__ when later f is accessed as an attribute of X or an instance thereof).

    Maybe you can better explain one toy use you'd want for your decorator, so we can be of more help...?

    Edit: this goes for decorators with arguments, too, i.e.

    class X(object):
    
      @deco(23)
      def f(self): pass
    

    then it's deco(23)(f) that's called in the class body, f is still a function object when passed as the argument to whatever callable deco(23) returns, and that callable should still return a function object (generally -- with exceptions;-).

提交回复
热议问题