gpt4 book ai didi

python - Python 装饰器可以用来返回非函数对象吗?

转载 作者:行者123 更新时间:2023-12-02 08:52:11 25 4
gpt4 key购买 nike

在Python中,你能编写一个返回非函数对象(如字符串或字典)的装饰器吗?例如,考虑以下代码:

def decorator(function):
return str(function)

@decorator
def foo(bar):
return bar + 1

此代码有效,但它是社区内可接受的做法吗?

最佳答案

引用 PEP 0318:

The current syntax for function decorators as implemented in Python 2.4a2 is:

@dec2
@dec1
def func(arg1, arg2, ...):
pass

This is equivalent to:

def func(arg1, arg2, ...):
pass
func = dec2(dec1(func))

without the intermediate assignment to the variable func.

因此,为了回答您的问题,您可以让装饰器返回非函数的内容,并且行为已完全定义。否则,它不会等同于上面的代码。

但是,这样做会非常不清楚。人们期望函数装饰器返回函数(或至少可调用对象),而类装饰器返回类。如果您偏离了这种模式,请自行承担风险 - 如果您的邻居出于愤怒和沮丧而决定拆掉您的隔间,那就是您的问题了:)。

关于python - Python 装饰器可以用来返回非函数对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20791056/

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