【问题标题】:Varirable scopes in python [duplicate]python中的变量范围[重复]
【发布时间】:2020-08-14 12:41:51
【问题描述】:

为什么 intlist 在 Python 中的作用域不同?下面是我的例子

#!/usr/bin/python

class Foo:
    def method(self):
        l = []
        i = 0
        def method1():
            l.append(1)
            i =  i + 1 <<<<<< Throws exception
        method1()
    Foo().method()

在上面的示例中,我可以访问method1 函数中的列表l,但不能访问整数i。有什么可能的解释吗?

我参考了下面的链接,但它没有对上述情况进行解释。

Short description of the scoping rules?

【问题讨论】:

  • 因为您在method1 中分配给i(但不是l)。如果你在函数中赋值给一个变量,除非你另外指定,否则该变量是函数的局部变量。
  • 是的,在函数内部分配的任何变量默认都是局部变量。

标签: python scope global-variables


【解决方案1】:

正如@khelwood 已经在评论部分回答的那样,这是作业。 您引用列表,但分配一个 int。 如果你引用 int 它也可以作为列表工作:

class Foo:
    def method(self):
        l = []
        i = 0
        def method1():
            l.append(1)
            m = i + 1
            print(m)
        method1()
Foo().method()

【讨论】:

    猜你喜欢
    • 2013-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-27
    • 2015-08-20
    • 1970-01-01
    • 2016-09-25
    • 1970-01-01
    相关资源
    最近更新 更多