python学习:1.5.4递归和闭包

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/bq_cui/article/details/90052412

对我来说闭包是块大生肉。

# -*- coding: utf-8 -*-
"""
Created on Thu May  9 17:32:57 2019

@author: Administrator
"""

# 递归函数
def addn(n):
    if n == 1:
        return 1
    return n + addn(n - 1)

print('递归:', addn(100))

#闭包
def adderx(x):
    def addery(y):
        return x + y
    return addery
    
s = adderx(1)
print('闭包:',s(100))

def counter(name):
    c = [0]
    def count():
        c[0] += 1
        if c[0] == 1: print('this is the', '1st', 'access to', name)
        elif c[0] == 2: print('this is the', '2nt', 'access to', name)
        elif c[0] == 3: print('this is the', '3rd', 'access to', name)
        else:  print('this is the', repr(c[0]), 'th access to', name)
    return count

print('a--------------')
a = counter('example')
print(a())
print(a())
print(a())
print(a())

print('b--------------')
a = counter('example')
print(a())
print(a())

运行:

递归: 5050
闭包: 101
a--------------
this is the 1st access to example
None
this is the 2nt access to example
None
this is the 3rd access to example
None
this is the 4 th access to example
None
b--------------
this is the 1st access to example
None
this is the 2nt access to example
None

猜你喜欢

转载自blog.csdn.net/bq_cui/article/details/90052412