【问题标题】:Below code is weird下面的代码很奇怪
【发布时间】:2014-06-01 13:37:10
【问题描述】:
    >>> def counter(start_at=0):
...     count = [start_at]
...     def incr():
...             count[0] += 1
...             return count[0]
...     return incr
...
>>> count = counter(7)
>>> print count()
8
>>> print count()
9

上面的代码运行良好。我明白。但我认为下面的代码应该和上面的一样。

    >>> counter(7)()
8
>>> counter(7)()
8

嗯,它不像 print count()。为什么?

【问题讨论】:

标签: python closures


【解决方案1】:

这样做的原因是每个counter(7) 调用都会创建一个单独的count 实例和单独的incr 函数。当你调用它们时,你实际上引用了不同的变量count,因此结果如上所示。

【讨论】:

  • 谢谢。你说得很清楚。但我还有一个问题。当代码 count=counter(7) 运行时。我认为 counter() 函数应该已经完成​​了。所以对 count[0] 的访问应该是非法的,对吧?那为什么count可以继续访问count[0]呢?提前致谢
  • @MingweiLi,这是因为Python中的变量实际上是对对象的引用,当根本没有引用指向它们时,对象就会被删除。 counter() 返回一个函数,该函数在内部引用由 counter() 调用创建的内部变量。只要返回的函数存在,内部对象就会存在并且可用。
【解决方案2】:

如果您想要计数器和计数的相同行为,请遵循以下代码:

>>> count = counter
>>> print count(7)
8
>>> print count(7)
8

【讨论】:

    猜你喜欢
    • 2021-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-24
    • 2014-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多