我正在尝试在我的应用程序中实现一个简单的日志记录功能。
class messages(object):
# Implement decorator here
def on(self):
def wrapper():
# Do something here
return wrapper
def off(self):
def wrapper():
# Do something here
return wrapper
class website(object):
@messages.on #This line can be switched on/off
def login(self):
# Do a whole bunch of stuff here
self.response = "[+] Login Succeeded!"
website = website()
website.login() # prints self.response based on @messages.on/off
但我不确定我需要在我的装饰器中应用什么。我尝试过创建实例并添加参数,但大多数情况下都会收到 TypeError。我对装饰器相当陌生。任何帮助将不胜感激,我很乐意下次记住这一点。
最佳答案
如果您只想让狗吠叫(如示例中所示),则无需启用装饰器
class Dog(object): def __init__(self): self.sound = "Woof!" def bark(self): return self.sound
如果您想为类中的某些函数启用日志记录,可以使用以下代码来实现此目的,并在注释中进行说明
from functools import wraps class Utilities(object): @staticmethod # no default first argument in logger function def logger(f): # accepts a function @wraps(f) # good practice https://docs.python.org/2/library/functools.html#functools.wraps def wrapper(self, *args, **kwargs): # explicit self, which means this decorator better be used inside classes only print("Before:", self.sound) result = f(self, *args, **kwargs) print("After:", self.sound) return result return wrapper class Dog(object): def __init__(self): self.sound = "Woof!" @Utilities.logger def run(self): """Perform running movement""" print("Running")
示例:
>>> dog = Dog()
>>> dog.run()
Before: Woof!
Running
After: Woof!
尽管毕竟没有必要在 Utilities
类中存储装饰器功能 - 最好有一个名为 utils
的单独模块(文件)并将装饰器放在那里作为独立功能
关于python - 在类中使用装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39931089/