python中修饰符@的用法
python中修饰符@的好处:可以极大的简化代码,动态修改函数功能,避免重复性代码,类似于c++的宏和java的注解。可以修饰约束方法和类,分为带参数和不带参数,影响原来的输出。官方使用说明:https://www.python.org/dev/peps/pep-0318/
不带参数的单一使用
def modifier(function):
def sayhello(*args):
print("hello, nice to meet you!")
function(*args)
return sayhello
@modifier
def test(a,b)
print(a*b)
if __name__=='__main__':
test(3,4)
执行结果
hello, nice to meet you!
12
不带参数的多次使用
def modifier(function):
def sayhello(*args):
print("hello, nice to meet you!")
function(*args)
return sayhello
def modifier1(function):
def sayhello1(*args):
print("hello, nice to meet you too!")
function(*args)
return sayhello1
@modifier
@modifier1
def test(a,b):
print(a*b)
if __name__=='__main__':
test(3,4)
执行结果
hello, nice to meet you!
hello, nice to meet you too!
12