[英]Class decorators for methods in classes
类中方法的 class 装饰器如何工作? 这是我通过一些实验所做的示例:
from functools import wraps
class PrintLog(object):
def __call__(self, func):
@wraps(func)
def wrapped(*args):
print('I am a log')
return func(*args)
return wrapped
class foo(object):
def __init__(self, rs: str) -> None:
self.ter = rs
@PrintLog()
def baz(self) -> None:
print('inside baz')
bar = foo('2')
print('running bar.baz()')
bar.baz()
这工作得很好。 但是,我的印象是不需要使用()
调用装饰器,但是当我从@PrintLog()
中删除括号时,出现此错误:
def baz(self) -> None:
TypeError: PrintLog() takes no arguments
有什么我想念/不明白的吗? 我也尝试过使用__init__()
传递一个一次性的 arg,它可以工作。
class PrintLog(object):
def __init__(self, useless):
print(useless)
def __call__(self, func):
@wraps(func)
def wrapped(*args):
print('I am a log')
return func(*args)
return wrapped
class foo(object):
def __init__(self, rs: str) -> None:
self.ter = rs
@PrintLog("useless arg that I'm passing to __init__")
def baz(self) -> None:
print('inside baz')
同样,这可行,但我不想将任何参数传递给装饰器。
tl;博士: python 3.x 中的这个问题。
帮助表示赞赏!
Class 装饰器接受 function 作为__init__
方法中的主题(因此是日志消息),因此您的装饰器代码应如下所示:
class PrintLog(object):
def __init__(self, function):
self.function = function
def __call__(self):
@wraps(self.function)
def wrapped(*args):
print('I am a log')
return self.function(*args)
return wrapped
抱歉,如果这不起作用,我正在我的移动设备上回答。
您缺少一张大图。
@decorator
def foo(...):
function_definition
几乎相同(除了一些内部修饰)
temp = foo
foo = decorator(temp)
装饰器是什么并不重要,只要它可以像 function 一样工作。
您的示例等效于:
baz = PrintLog("useless thing")(<saved defn of baz>)
由于PrintLog
是 class, PrintLog(...)
创建PrintLog
的实例。 该实例有一个__call__
方法,因此它可以像 function 一样工作。
一些装饰器设计为采用 arguments。 一些装饰器被设计成不带 arguments。 Some, like @lru_cache
, are pieces of Python magic which look to see if the "argument" is a function (so the decorator is being used directly) or a number/None, so that it returns a function that then becomes the decorator.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.