简体   繁体   English

从python函数内部访问全局变量

[英]Accessing global variables from inside python functions

I'm trying to update either the variable one or two from inside the calc function and then print it in the rob function. 我正在尝试从calc函数内部更新一个或两个变量,然后在rob函数中将其打印出来。 But whenever I do it, its reverted back to zero and thats causing problems 但是每当我这样做时,它就会恢复为零,这会导致问题

Used the global keyword as mentioned Using global variables in a function and can't access global variable from inside a function in python but that doesnt seemed to work 如前所述使用 global关键字在函数使用全局变量,并且无法从python中的函数内部访问全局变量,但这似乎不起作用

class Solution(object):
    one=0
    two= 0
    def calc(self,root,flag):
        global one
        global two
        if root == None:
            return
        if flag:
            self.one+=root.val
            Solution().calc(root.left,False)
            Solution().calc(root.right, False)
        else :
            self.two+=root.val
            Solution().calc(root.left, True)
            Solution().calc(root.right, True)
        print (str(root.val)+" " + str(self.one) + " " + str(self.two))
    def rob(self, root):
        self.calc(root,True)
        global one
        global two        
        print self.one
        print self.two
        return max(self.one,self.two)

Its basically​ always reverting one and two back to zero 它基本上总是将一和二恢复为零

Without the definition of root and a sample invocation of code that is giving the incorrect answer it's hard to answer your question. 如果没有root的定义和没有给出错误答案的代码示例调用,那么很难回答您的问题。 That said, I think that the issue is that you're asigning root.val to a Solution attribute not incrementing the globals: 就是说,我认为问题在于您正在将root.val root.valSolution属性,而不会增加全局变量:

# You have:
self.one += root.val
# You want:
one += root.val

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM