gpt4 book ai didi

python - 第一次使用装饰器,我错过了什么?

转载 作者:行者123 更新时间:2023-12-05 09:04:01 24 4
gpt4 key购买 nike

class User:
def __init__(self):
self.score = 0
self.wins = 0
self.losses = 0


def tally(self, func):
def wrapper_function(w):
print("Wins: {}\nLosses: {}\nTotal Score: {}".format(self.wins, self.losses, self.score))
return func(w)
return wrapper_function()

@tally
def record_win(self, w=1):
self.wins += w


user1 = User()
user1.record_win()

我得到的错误是:TypeError: tally() missing 1 required positional argument: 'func'

编辑 这篇文章不同于here因为在那篇文章中装饰器函数不是实例方法..我现在看到它增加了一些特殊的要求。

最佳答案

你的问题是你将 tally 定义为一个实例方法,但它实际上只是一个装饰函数(它不能以任何合理的方式在实例上调用)。如果你坚持,你仍然可以在类中定义它(它只是对实例没用),你只需要让它接受一个参数(要包装的函数),没有 self,并使 < em>wrapper 接受 self(同时将任何提供的参数传递给包装函数):

class User:
# ... other methods unchanged ...
def tally(func):
def wrapper_function(self, *args, **kwargs): # Accept self + arbitrary arguments to make decorator useable on more functions
print("Wins: {}\nLosses: {}\nTotal Score: {}".format(self.wins, self.losses, self.score))
return func(self, *args, **kwargs) # Pass along self to wrapped function along with arbitrary arguments
return wrapper_function # Don't call the wrapper function; you have to return it so it replaces the decorated function

@tally
def record_win(self, w=1):
self.wins += w

# Optionally, once tally is no longer needed for new methods, but before dedenting out of class definition, do:
del tally
# so it won't stick around to appear as a possible method to call on instances
# It's done all the work it needs to do after all

删除 w 参数以支持 *args, **kwargs 意味着您不需要专注于特定的函数原型(prototype),也不需要复制函数的默认值你正在包装(如果他们不传递参数,默认值将自动使用)。

关于python - 第一次使用装饰器,我错过了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69127485/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com