gpt4 book ai didi

python - 了解 Python 装饰器

转载 作者:行者123 更新时间:2023-12-01 00:59:56 24 4
gpt4 key购买 nike

我编写了一小段代码来自己运行它并了解流程:

def perform_arithmetic_ops(func):
print("INSIDE PERFORM ARTITHMETIC")
def decorate(*args):
print("I JUST GOT DECORATED")
print(f"SUM -> {args[0]+args[1]}")
func(args[0],args[1])
return decorate


@perform_arithmetic_ops
def print_me(x,y):
print(f"X = {x} ; Y = {y}")

print_me(5,4)

如果我的理解(我在下面的表格中总结)不正确,请纠正我。

  1. def perform_arithmetic_ops装饰器只接受一个可调用对象,在本例中是一个函数作为其参数,对吗?

  2. 内部函数def decorate()这是实际执行所需修改的内容。我注意到评论是func(args[0],args[1])里面def decorate()基本上意味着 X={x} ; Y={y}声明没有被打印。那么这是否意味着装饰器取代了原始函数所做的一切?如果是的话,如何修改?它不是更多地替代另一个功能吗?

  3. return decorate()即调用decorate()而不是返回它导致元组索引超出范围的错误。为什么?

最佳答案

仔细看看这个巨大的answer/novel 。这是我遇到过的最好的解释之一。

def perform_arithmetic_ops is the decorator which only takes a callable object, in this case a function as its argument, correct?

是的。你说得对。

The inner function def decorate() here is what actually performs the desired modification. What I noticed was commenting func(args[0],args[1]) inside def decorate() basically meant that the X={x} ; Y={y} statement wasn't being printed. So does this mean that the the decorator replaces everything the original function does? If yes, how is that a modification? Isn't it more of a replacement for another function?

装饰器是一个将函数作为其唯一参数并返回一个函数的函数。这有助于一遍又一遍地使用相同的代码“包装”功能。它是包装但不是修改。

return decorate() i.e. calling decorate() instead of returning it led to errors for tuple index out of range. Why?

要了解装饰器,您必须首先了解函数是 Python 中的对象。

因为您可能会在不带任何参数的情况下调用它。试试这个返回装饰(5,1)。但是在这个语句之后,如果您尝试装饰像 print_me 这样的函数,那么 print_me 可能会持有不可调用的对象。看这个:

def perform_arithmetic_ops(func):
print("INSIDE PERFORM ARTITHMETIC")
def decorate(*args):
print("I JUST GOT DECORATED")
print(f"SUM -> {args[0]+args[1]}")
return func(args[0], args[1])
return decorate(5, 1)


@perform_arithmetic_ops
def print_me(x,y):
print(f"X = {x} ; Y = {y}")
return 5


# print_me(5,2) # Will throw: TypeError: 'int' object is not callable
print(print_me)

关于python - 了解 Python 装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55889154/

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