具有两个内部函数python的闭包

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

我试图用两个内部函数编写一个闭包,但我收到以下错误

def factory(n=0):
#n=0

    def current():
       return n
    return current
    def counter():
        n=n+1
        return n
    return counter


  f_current,f_counter = int(input())

  print(f_counter())
  print(f_current())

我有以下错误:

   >>4
   Traceback (most recent call last):
   File "C:/Users/lokesh/Desktop/python/closure3.py", 
    line 13, in <module>
   f_current,f_counter = int(input())
   TypeError: 'int' object is not iterable

我的要求是在给出输入4之后,它应该显示:

  4
  5

我是python的新手,有人可以帮助我......提前感谢

python closures
1个回答
1
投票

看起来更像你想要的东西:

def factory(n=0):

    def current():
        return n

    def counter():
        nonlocal n
        n += 1
        return n

    return current, counter

f_current, f_counter = factory()

print(f_current())
print(f_counter())
print(f_current())
print(f_counter())

输出:

0
1
1
2

4为输入:

f_current, f_counter = factory(4)
print(f_current())
print(f_counter())

4
5

factory()返回两个内部函数。您需要使用nonlocal来增加封闭函数的n。没有nonlocal你将无法修改n但会得到:

UnboundLocalError: local variable 'n' referenced before assignment

因为n只是一个局部变量。 nonlocal n从内部函数内部可修改的封闭函数中生成n。在n中评估current很好,因为Python的作用域规则允许从外部作用域读取变量,这是从封闭函数的范围。

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