【问题标题】:Why is a global dictionary accessible inside a class whereas a global integer variable is not? [duplicate]为什么全局字典可以在类内部访问,而全局整数变量不能? [复制]
【发布时间】:2019-09-22 16:43:42
【问题描述】:

我已经声明了一个全局字典和一个变量。现在,当在一个类中访问两者时,我可以访问字典,但要访问另一个变量,我得到UnboundLocalError。为了解决这个问题,我使用了这行代码:global curr_length,然后访问它并运行。但我想知道为什么普通整数变量需要这行额外的代码,而字典不需要?

代码是:

memoized = {}
curr_length = 0
curr_pal = ""


class Solution:
    def check_palindrome(self, str_):
        if len(str_) <= 1:
            return False
        global curr_length
        if len(str_) <= curr_length:
            return False
        if memoized.get(str_, None):
            return memoized[str_]
        if str_ == str_[::-1]:
            memoized[str_] = True
            curr_length = len(str_)
            return True
        memoized[str_] = False
        return False

    def longest_palindrome(self, str_, starting_index):
        if len(str_) <= 1:
            return None
        n = len(str_)
        if self.check_palindrome(str_[starting_index:n]):
            return str_
        n -= 1
        self.longest_palindrome(str_[starting_index:n], starting_index)

    def longestPalindrome(self, s: str) -> str:
        for starting_index in range(len(s)):
            pal = self.longest_palindrome(s, starting_index)
            if pal:
                return pal
        return ""


solution = Solution()
print(solution.longestPalindrome("babad"))

【问题讨论】:

  • 当您从方法中删除global curr_length 时会发生什么?

标签: python class oop


【解决方案1】:

短:

您正试图在查找本地 curr_length 变量的函数中使用 curr_length = len(str_) 更改 curr_length 的值,但找不到它。它需要global curr_length 行才能知道它是一个global 变量。

至于为什么您想知道为什么 dict 对象不需要 global memoized 行,您应该阅读以下答案: Global dictionaries don't need keyword global to modify them?Why is the global keyword not required in this case?

解释:

在 Python 中,在函数之外或在全局范围内声明的变量称为全局变量。这意味着,全局变量可以在函数内部或外部访问。

让我们看一个关于如何在 Python 中创建全局变量的示例。

x = "global"

def foo():
    print("x inside :", x)

foo()
print("x outside:", x)

当我们运行代码时,将会输出:

x inside : global
x outside: global

在上面的代码中,我们创建了一个全局变量 x 并定义了一个 foo() 来打印全局变量 x。最后,我们调用 foo() 来打印 x 的值。

如果你想在函数中改变 x 的值怎么办?

def foo():
    x = x * 2
    print(x)
foo()

当我们运行代码时,将会输出:

UnboundLocalError: local variable 'x' referenced before assignment

输出显示错误,因为 Python 将 x 视为局部变量,并且 x 也未在 foo() 中定义。

为了完成这项工作,我们使用 global 关键字

【讨论】:

  • 您需要添加更多关于如何使用global的说明。 AFAICT,OP 正在按照您的链接建议使用 curr_length 变量
  • 答案是试图解释他试图用curr_length = len(str_)改变curr_length的值
  • 那么这与他们的字典有什么关系?
  • 他 OP 使用了 global 关键字和 curr_length,正如您的链接所建议的那样
猜你喜欢
  • 1970-01-01
  • 2019-05-04
  • 2013-07-03
  • 2021-06-20
  • 2012-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多