基础套娃
先看一个简单的函数`
def test():
print("just a test code")
再看下面两行——
test_ins = test
test_ins()
第一行什么也不会发生,只是创建了一个名为test_ins的对象,指向了函数test
第二行,由于末尾多了(),实际上相当于test(),换言之函数test会被执行,进而打印出just a test code
我们再来写个更复杂一些的套娃……我是说嵌套
def test_2():
def test_3():
print("just a test code again!")
return test_3
test_2()内部嵌套了函数test_3,并且返回了函数test_3
请注意,test_3函数被返回了,但是并没有被执行,如果你通过test_2()来执行函数,不会打印任何东西,而是返回给你一个名叫test_3的函数,简言之——
test_2()结果是test_3
我们可以通过__name__属性来验证这件事——
print(test_2().__name__)
结果将会是——
test_3
当然,如果你访问的是test_2的__name__属性,也就是print(test_2.name),结果将会是——
test_2
带()才会执行,反之则只是访问函数对象本身。由于test_2执行的时候返回了test_3,也就出现了如上的访问__name__不一样的情况。
进一步套娃
继续看下面这个例子
def testL1():
def testL2():
def testL3():
print("just a test code again and again!")
return testL3
print(testL2.__name__)
return testL2
print(testL1().__name__)
在这个例子中,函数testL1运行时返回函数testL2,函数testL2运行时返回函数testL3,函数testL3运行时打印一串字符串
第一句print调用在testL1函数内部,所以只要testL1运行,就会打印testL2的名字,由于此时testL2并没有运行,所以预期结果应该是testL2
同时由于testL1的执行结果是返回函数testL2,所以第二句print的结果也将是testL2
运行结果
testL2
testL2
而如果对代码做小小的修改
def testL1():
def testL2():
def testL3</