Python3 有条件装饰?
是否可以根据条件装饰函数?
a'la:
if she.weight() == duck.weight():
@burn
def witch():
pass
我只是想知道是否可以使用逻辑(当 witch
被调用时?)来确定是否用 @burn 装饰
witch
?
如果没有,是否可以在装饰器中创建一个条件以达到相同的效果? (女巫
被称为未修饰的。)
Is it possible to decorate a function based on a condition?
a'la:
if she.weight() == duck.weight():
@burn
def witch():
pass
I'm just wondering if logic could be used (when witch
is called?) to figure out whether or not to decorate witch
with @burn
?
If not, is it possible to create a condition within the decorator to the same effect? (witch
being called undecorated.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以创建一个“有条件”装饰器:
用法示例如下:
You can create a 'conditionally' decorator:
Usage example follows:
可以通过重新分配启用/禁用装饰器。
It is possible to enable/disable decorators by reassignment.
装饰器只是用于重新定义函数的语法糖,例如:
这意味着您可以在语法糖存在之前以旧的方式进行操作:
Decorators are just syntactical sugar for re-defining the function, ex:
Which means that you could do it the old way, before the syntactical sugar existed:
要创建条件装饰器,您可以创建一个接受参数的装饰器,如下所示
To create a conditional decorator you can create a decorator which accepts arguments as below