简体   繁体   English

Python 中对局部和全局变量 scope 的说明

[英]Clarification on local and global variable scope in Python

I'm a bit confused regarding local and global variables referenced outside a function scope.对于在 function scope 之外引用的局部和全局变量,我有点困惑。 For one problem, I had this code and it worked:对于一个问题,我有这段代码并且它有效:

def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool:
    l1 = []
    l2 = []
        
    def traverseLeaf(root: TreeNode, sequence: list): 
        if not root: return 
        elif not root.left and not root.right: sequence.append(root.val)
        else: 
            traverseLeaf(root.left, sequence)
            traverseLeaf(root.right, sequence)
                
    traverseLeaf(root1, l1)
    traverseLeaf(root2, l2)
        
    return l1 == l2

You can see I reference the list object outside the function scope.您可以看到我在 function scope 之外引用了列表 object。 However, if I try this:但是,如果我尝试这个:

# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def convertBST(self, root: TreeNode) -> TreeNode:
        total = 0
               
        def rightOrderTraversal(node: TreeNode):
            if not node: return
            elif not node.left and not node.right: 
                total += node.val
                node.val = total
            else: 
                rightOrderTraversal(node.right)
                total += node.val
                node.val = total
                rightOrderTraversal(node.left)                
            
        rightOrderTraversal(root)
        return root

It does not work, and the error says I reference total as a local variable when calling rightOrderTraversal .它不起作用,并且错误说我在调用rightOrderTraversal时将 total 引用为局部变量。 What kind of variables does Python create local references for? Python 为哪些变量创建局部引用? From these examples, it seems like Python references lists outside the function scope but not ints.从这些示例中,似乎 Python 引用了 function scope 之外的列表,但不是整数。

I also tried to make total global as a way to solve the issue, but that didn't work.我还尝试将total global作为解决问题的一种方式,但这并没有奏效。

If you want to use a variable that is visible to any methods/sub functions within an object instance, you use the "self" to reference to the object instance, eg:如果要使用对 object 实例中的任何方法/子函数可见的变量,则使用“self”来引用 object 实例,例如:

class Solution:
   
    def my_method(self, total):
        self.total = total
               
        def my_function(total):
            self.total += total

        my_function(total)

s = Solution()
s.my_method(1)
print(s.total)

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

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