gpt4 book ai didi

python - 是否可以使用带参数的 Python 类装饰器?

转载 作者:太空狗 更新时间:2023-10-30 02:06:20 24 4
gpt4 key购买 nike

我想做的是:

@add_cache(cache_this, cache_that, cache_this_and_that)
class MyDjangoModel(models.Model):
blah

但失败了,因为第一个参数似乎隐式地是实际的类对象。是否有可能解决这个问题,或者我是否被迫使用丑陋的语法而不是这种漂亮的语法?

最佳答案

您的 arg_cache 定义需要执行如下操作:

def arg_cache(cthis, cthat, cthisandthat):
def f(obj):
obj.cache_this = cthis
obj.cache_that = cthat
obj.thisandthat = cthisandthat
return obj
return f

@arg_cache(cache_this, cache_that, cache_this_and_that)
...

该示例假设您只想在装饰类上设置一些属性。您当然可以用这三个参数做其他事情。

关于python - 是否可以使用带参数的 Python 类装饰器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4262892/

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