加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python如何使用非局部效应处理内部函数?

发布时间:2020-12-20 11:49:26 所属栏目:Python 来源:网络整理
导读:考虑以下函数,我们希望在整数a上不是常数,但总是返回(1,2): def foo(a): b = 1 c = 2 def bar(b,c): b = b + a c = c + a bar(b,c) return (b,c) 如果我理解正确,实现bar(b,c)的惯用方法是根本不给它任何参数,并在其定义中声明b和c非局部.然而,我很好奇:我
考虑以下函数,我们希望在整数a上不是常数,但总是返回(1,2):

def foo(a):
    b = 1
    c = 2
    def bar(b,c):
        b = b + a
        c = c + a
    bar(b,c)
    return (b,c)

如果我理解正确,实现bar(b,c)的惯用方法是根本不给它任何参数,并在其定义中声明b和c非局部.然而,我很好奇:我们如何使内部函数对其参数产生非局部效应?

解决方法

正如 this answer中针对Python 2.x所述:

Python doesn’t allow you to reassign the value of a variable from an
outer scope in an inner scope (unless you’re using the keyword
“global”,which doesn’t apply in this case).

这将返回(2,3):

def foo(a):
    b = 1
    c = 2
    def bar(b,c):
        b = b + a
        c = c + a
        return b,c
    b,c = bar(b,c)

print(foo(1))

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读