【发布时间】:2020-12-03 17:57:04
【问题描述】:
注意:
我在这里有一个相关的问题:
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。试验一:身份丢失
下面的装饰器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
有细微的差别,但我不知道为什么。
【问题讨论】:
-
因为在我的版本中,它返回一个方法对象,对于
==,它的评估结果为真,但它创建了两个不同的对象......有点碍事:a = [1,2]; b = [1,2],然后是@987654346 @ 但不是a is b
标签: python python-3.x decorator python-decorators