<分区>
注意:
我在这里有一个相关的问题:
How to access variables from a Class Decorator from within the method it's applied on?
我打算编写一个相当复杂的装饰器。因此,装饰器本身应该是它自己的一个类。我知道这在 Python (Python 3.8) 中是可能的:
import functools
class MyDecoratorClass:
def __init__(self, func):
functools.update_wrapper(self, func)
self.func = func
def __call__(self, *args, **kwargs):
# do stuff before
retval = self.func(*args, **kwargs)
# do stuff after
return retval
@MyDecoratorClass
def foo():
print("foo")
现在,当我尝试在方法 而不仅仅是函数上应用装饰器时,我的问题就开始了——尤其是当它是来自另一个类的方法 时。让我向您展示我的尝试:
1。试验一:identity loss
下面的装饰器 MyDecoratorClass
不(或不应该)做任何事情。它只是样板代码,可以稍后使用。 Foobar
类中的方法 foo()
打印调用它的对象:
import functools
class MyDecoratorClass:
def __init__(self, method):
functools.update_wrapper(self, method)
self.method = method
def __call__(self, *args, **kwargs):
# do stuff before
retval = self.method(self, *args, **kwargs)
# do stuff after
return retval
class Foobar:
def __init__(self):
# initialize stuff
pass
@MyDecoratorClass
def foo(self):
print(f"foo() called on object {self}")
return
现在您在这里观察到的是 foo()
方法中的 self
被交换了。它不再是 Foobar()
实例,而是 MyDecoratorClass()
实例:
>>> foobar = Foobar()
>>> foobar.foo()
foo() called from object <__main__.MyDecoratorClass object at 0x000002DAE0B77A60>
换句话说,foo()
方法失去了它原来的身份。这将我们带到下一个试验。
2。试验二:保持身份,但崩溃
我试图保留 foo()
方法的原始身份:
import functools
class MyDecoratorClass:
def __init__(self, method):
functools.update_wrapper(self, method)
self.method = method
def __call__(self, *args, **kwargs):
# do stuff before
retval = self.method(self.method.__self__, *args, **kwargs)
# do stuff after
return retval
class Foobar:
def __init__(self):
# initialize stuff
pass
@MyDecoratorClass
def foo(self):
print(f"foo() called on object {self}")
return
现在让我们测试一下:
>>> foobar = Foobar()
>>> foobar.foo()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 7, in __call__
AttributeError: 'function' object has no attribute '__self__'
哎呀!
编辑
感谢@AlexHall 和@juanpa.arrivillaga 提供的解决方案。他们都工作。但是,它们之间存在细微差别。
我们先来看看这个:
def __get__(self, obj, objtype) -> object:
temp = type(self)(self.method.__get__(obj, objtype))
print(temp)
return temp
我引入了一个临时变量,只是为了打印 __get__()
返回的内容。每次访问方法 foo()
时,此 __get__()
函数都会返回一个新的 MyDecoratorClass()
实例:
>>> f = Foobar()
>>> func1 = f.foo
>>> func2 = f.foo
>>> print(func1 == func2)
>>> print(func1 is func2)
<__main__.MyDecoratorClass object at 0x000001B7E974D3A0>
<__main__.MyDecoratorClass object at 0x000001B7E96C5520>
False
False
第二种方法(来自@juanpa.arrivillaga)不同:
def __get__(self, obj, objtype) -> object:
temp = types.MethodType(self, obj)
print(temp)
return temp
输出:
>>> f = Foobar()
>>> func1 = f.foo
>>> func2 = f.foo
>>> print(func1 == func2)
>>> print(func1 is func2)
<bound method Foobar.foo of <__main__.Foobar object at 0x000002824BBEF4C0>>
<bound method Foobar.foo of <__main__.Foobar object at 0x000002824BBEF4C0>>
True
False
有细微差别,但我不确定原因。