为什么在类内部可以访问全局字典而不能在全局整数变量中访问全局字典? [英] Why is a global dictionary accessible inside a class whereas a global integer variable is not?

查看:83
本文介绍了为什么在类内部可以访问全局字典而不能在全局整数变量中访问全局字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have declared a dictionary globally and a variable as well. Now, when accessing both in a class, I can access the dictionary but for accessing the other variable, I get the UnboundLocalError. For solving this, I used the line of code: global curr_length and then access it and it ran. But I wanted to known why is this additional line of code required for a normal integer variable whereas not required for a dictionary?

代码是:

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"))


推荐答案

简短:


您正在尝试更改 curr_length的值在函数内查找 curr_length 的函数中具有 curr_length = len(str _) ,并且找不到它。它需要行 global curr_length 知道它是 global 变量。

Short:

You are trying to change the value of curr_length with curr_length = len(str_) inside a function which looks for a local curr_length variable, and can't find it. It needs the line global curr_length to know that it's a global variable.

至于为什么您想知道为什么 dict 对象不需要全局存储的行,您应该请阅读以下答案:
全球词典不要是否需要全局关键字来修改它们?为什么在这种情况下不需要全局关键字?

As far as why you're wondering as to why a dict object does not need global memoized line, you should read the answer to: Global dictionaries don't need keyword global to modify them? or Why is the global keyword not required in this case?

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

In Python, a variable declared outside of the function or in global scope is known as global variable. This means, global variable can be accessed inside or outside of the function.

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

Let's see an example on how a global variable is created in Python.

x = "global"

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

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

运行代码时,输​​出将为:

When we run the code, the will output be:

x inside : global
x outside: global

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

In above code, we created x as a global variable and defined a foo() to print the global variable x. Finally, we call the foo() which will print the value of x.

如果要在函数内更改x的值怎么办?

What if you want to change value of x inside a function?

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

运行代码时,输​​出将为:

When we run the code, the will output be:

UnboundLocalError:之前引用的本地变量'x'分配

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

The output shows an error because Python treats x as a local variable and x is also not defined inside foo().

为完成这项工作,我们使用全局关键字

To make this work we use global keyword

这篇关于为什么在类内部可以访问全局字典而不能在全局整数变量中访问全局字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆