我正在尝试用装饰器类装饰实例方法,但是它无法将实例作为Bar -> 117
Foo -> 42
VeryVeryLongName -> 101
传递给装饰的可调用对象。包装到self
也不起作用,因为在构建装饰器类时,包装的方法尚不可用:
@wraps
如何在#!/usr/bin/env python3
"""Trying to decorate a method."""
class Wrap:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
print("self: {self}\n*args: {args}\nkwargs: {kwargs}".format(
self=self, args=args, kwargs=kwargs))
self.func(self=args[0], a=3.141)
class A:
@Wrap
def aaa(self, a=None):
print("My instance: {}\na = {}".format(self, a))
a = A()
a.aaa(1000)
# My instance: 1000
# a = 3.141
## The object "a" is not passed on, rendering aaa effectively a static method.
a.aaa(a, 1000)
# My instance: <__main__.A object at 0x7fe371579be0>
# a = 3.141
## The expected result for the first attempt.
内部访问a
,而无需显式传递它?