无法理解局部变量和全局变量的工作方式

时间:2019-12-05 20:17:43

标签: python global-variables local-variables

作为一名新的python学习者,我非常感谢您的建议,为什么我对以下情况的理解是错误的:

当我编写如下代码时:

class Solution(object):

    def isHappy(self, n):
        seen = {}
        while n!=1 and n not in seen.keys():
            seen[n] = '*'
            n = self.get_next(n)
        return n==1

    total_sum = 0
    def get_next(self,no):

        while no>0:
            no,v = divmod(no,10)
            total_sum+=v**2
        return total_sum
test55 = Solution()
test55.isHappy(56)

但是它抛出了一个错误消息:“在赋值之前引用了局部变量'total_sum'”,我认为它应该起作用,因为:尽管我们没有在get_next函数内部初始化total_sum,但我希望它应该在函数外部寻找total_sum 。谁能分享一些我为什么错的建议?

如果我们将total_sum放入get_next函数中,那么它将起作用:

class Solution(object):

    def isHappy(self, n):
        seen = {}
        while n!=1 and n not in seen.keys():
            seen[n] = '*'
            n = self.get_next(n)
        return n==1


    def get_next(self,no):
        total_sum = 0
        while no>0:
            no,v = divmod(no,10)
            total_sum+=v**2
        return total_sum
test55 = Solution()
test55.isHappy(56)

0 个答案:

没有答案