变量可以修饰吗?

问题描述 投票:0回答:1

Python 中的装饰函数或方法非常棒。

@dec2
@dec1
def func(arg1, arg2, ...):
    pass
#This is equivalent to:

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

我想知道是否可以在 python 中装饰变量。

@capitalize
@strip
foo = ' foo '

print foo # 'FOO'
#This is equivalent to:
foo = foo.strip().upper()

我通过搜索找不到任何有关该主题的内容。

python decorator python-decorators
1个回答
21
投票

不可以,装饰器语法仅对函数和类有效。

只需将值传递给函数即可:

foo = capitalize(strip(' foo '))

或用结果替换变量:

foo = ' foo '
foo = capitalize(strip(foo))

装饰器的存在是因为你不能只在函数调用中包装函数或类声明;您可以的简单变量。

© www.soinside.com 2019 - 2024. All rights reserved.