In Python, why do we need "self" for integers, but not arrays?
Anonymous User
52

I'm doing a lot of backtracking problems and I usually define an array to append to. However, I seem to never need the "self" keyword. However, if I'm defining an integer, the compiler will point out that I need the keyword "self". For example:

class Solution(object):
    def rangeSumBST(self, root, L, R):
        """
        :type root: TreeNode
        :type L: int
        :type R: int
        :rtype: int
        """
        self.total = 0 # need to use self
        answer = [] # don't need to use self
        
        def dfs(root):
            if root is None:
                return 
            if root.val >= L and root.val <= R:
                self.total += root.val
                dfs(root.left)
                dfs(root.right)
                answer.append(1)
            elif root.val >= L:
                dfs(root.left)
            elif root.val <= R:
                dfs(root.right)
        
        dfs(root)
        return self.total # need self, with the answer array I could just write "return answer"

I've searched up the self keyword but can't seem to understand why there are 2 different conventions for integers and not arrays. If anything, shouldn't they be consistent?

Comments (1)