在Python中的函数中对变量使用装饰器

时间:2017-06-06 09:37:59

标签: python variables decorator

我想使用装饰器来验证Python中的数据。 通常在Python中,在函数上使用装饰器,但我想在变量上使用装饰器,类似于Java:

public class Main {
   public static void main(String[] args) {
      @BoldWrapper
      @ItalicWrapper
      String str = "Hello World";
      // Display <b><i>Hello World</i></b>
   }
}

public @interface BoldWrapper {
    public void wrap() default "<b>" + str + "</b>";
}

public @interface ItalicWrapper {
    public void wrap() default "<i>" + str + "</i>";
}

所以在Python中我会有类似的东西:

if __name__ == '__main__':
    @BoldWrapper
    @ItalicWrapper
    str = "Hello World";

1 个答案:

答案 0 :(得分:1)

只有类和函数/方法定义可以修饰(函数/方法,因为 Python 2.4 ,类 Python 2.6 ):

来自function definition

的文档
  

函数定义可以由一个或多个装饰器表达式包装。在定义函数时,在包含函数定义的范围内计算Decorator表达式。

class definition

  

也可以修饰类:就像装饰函数一样

所以

@BoldWrapper
@ItalicWrapper
text = "Hello World"

将导致SynaxError

不需要此功能,因为我们只能编写函数调用

text = BoldWrapper(ItalicWrapper("Hello World"))

P上。 S上。

  • 不要为您的对象使用str等内置插件的名称,
  • 分号在 Python
  • 中是多余的

进一步阅读

相关问题