V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
JasonLaw
V2EX  ›  Python

关于 closure 的一个疑问

  •  
  •   JasonLaw · 2023-01-25 17:54:44 +08:00 · 1615 次点击
    这是一个创建于 428 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我正在阅读functional programming - Can you explain closures (as they relate to Python)? - Stack Overflow,在这个回答中有以下代码。

    def make_counter():
       i = 0
       def counter(): # counter() is a closure
           nonlocal i
           i += 1
           return i
       return counter
    
    c1 = make_counter()
    c2 = make_counter()
    
    print (c1(), c1(), c2(), c2())
    # -> 1 2 1 2
    

    我的疑问:ta 说 counter() is a closure ,应该是 counter is a closure ,对吧?

    第 1 条附言  ·  2023-01-26 13:08:18 +08:00

    来自NeetCode Discord server一个成员的回答:

    Yes they're different within a block of code. counter is a reference to a function. counter() is a call to a function named counter.

    Within comments () is usually used to indicate that the keyword/namespace is a function in my experience.

    For example counter() in text/comment/a book says "Function counter..."

    6 条回复    2023-01-28 10:38:04 +08:00
    Tyanboot
        1
    Tyanboot  
       2023-01-26 02:59:23 +08:00
    这里的注释里面的 counter() 应该是表达“counter 函数”的意思,而不是表达“counter 函数调用后返回的那个东西”的意思。

    加了个括号在后面只是为了表达类型,而不是真的在调用,正常来说不应该会有歧义的吧。
    gowl
        2
    gowl  
       2023-01-26 03:02:59 +08:00
    他想表达的是 counter 这个函数是 closure ,但是他用了 counter() 这种「调用」形式,不如你理解的 counter 这种「函数值」形式更准确。
    gowl
        3
    gowl  
       2023-01-26 03:09:17 +08:00
    如果用 ML 家族的语言来表述,可以说:counter 这个类型为 (unit -> int) 的值是一个 closure 。这样就没有歧义了。
    JasonLaw
        4
    JasonLaw  
    OP
       2023-01-26 07:40:46 +08:00
    @Tyanboot #1 counter()和 counter 它们两个完全是不同的东西,counter 才是一个 function 。
    yulon
        5
    yulon  
       2023-01-26 11:37:16 +08:00   ❤️ 1
    照你的逻辑,那么 def counter() 也是有语病的,你应该发明一个 def function counter 。

    实际上 def 里面的括号是用来装形参而不是实参的,调用时的括号才是用来装实参的,都是括号但是意义不一样。

    你要分清声明和表达式是两种东西,哪怕是纯 C 这种声明极度变态得像是表达式,它也还是个声明。

    反正我写 git commit 的时候都只会写 add foo() or add bar{},如果每次都写 function class ,又累又冗余。
    julyclyde
        6
    julyclyde  
       2023-01-28 10:38:03 +08:00
    这句注释写在 def counter()后边,那自然是用来解释 def 的
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3004 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 14:45 · PVG 22:45 · LAX 07:45 · JFK 10:45
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.