实例方法的Decorator类在调用中覆盖self

时间:2018-11-21 17:06:42

标签: python syntax decorator python-decorators self

是否可以构建一个装饰器类来跟踪外部类中的某些内容,并且仍然允许装饰后的方法正常调用?当为装饰器类实现 call 时,传递的self是装饰器实例,而不是该方法实际上被调用的实例。有办法解决吗?

class Outer:
  class Inner:
    def __init__(self, func):
      self.func = func

    def __call__(self, *args, **kwargs):
      pass
      # Something like return Inner-self.func(Outer-self, *args, **kwargs)

  def __init__(self, number):
    self.number = number

  @Inner
  def print_number(self):
    print(self.number)

instance = Outer(2)

instance.print_number()
# Should print 2

0 个答案:

没有答案