原
Python修饰符 (一)—— 函数修饰符 “@”
</div>
<link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-f57960eb32.css">
<div class="htmledit_views" id="content_views">
今天被问到Python函数修饰符,顺手写写。
Python函数修饰符,“@”,与其说是修饰函数倒不如说是引用、调用它修饰的函数。
举个栗子,下面的一段代码,里面两个函数,没有被调用,也会有输出结果:
- def test(f):
- print "before ..."
- f()
- print "after ..."
-
- @test
- def func():
- print "func was called"
直接运行,输出结果:
- before ...
- func was called
- after ...
上面代码可以看出来,只定义了两个函数: test和func。没有地方调用它们。如果没有“@test”,运行应该是没有任何输出的。
但是,Python解释器读到函数修饰符“@”的时候,后面步骤会是这样了:
1. 去调用 test函数,test函数的入口参数就是那个叫“func”的函数;
2. test函数被执行,入口参数的(也就是func函数)会被调用(执行);
换言之,修饰符带的那个函数的入口参数,就是下面的那个整个的函数。有点儿类似JavaScript里面的 function a (function () { ... });
再来看一个例子:
- def test(func):
- func()
- print "call test"
-
- def test1(f):
- f()
- print "call test1"
-
- def main():
- @test
- def fun():
- print "call fun"
- @test1
- def fun1():
- print "call fun1"
- main()
输出结果:
- call fun
- call fun1
- call test1
- call test
需要注意的:
1. 函数先定义,再修饰它;反之会编译器不认识;
2. 修饰符“@”后面必须是之前定义的某一个函数;
3. 每个函数只能有一个修饰符,大于等于两个则不可以。