开发者

Is it possible to have a Python class decorator with arguments?

What I'd like to do is this:

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

But fails because it seems that the first argument is implicitly the actual class obj开发者_StackOverflowect. Is it possible to get around this or am I forced to use the ugly syntax as opposed to this beautiful syntax?


Your arg_cache definition needs to do something like:

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)
...

The example assumes you just want to set some properties on the decorated class. You could of course do something else with the three parameters.


Write a callable that returns an appropriate decorator.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜