Home > Net >  Why does the value of this class variable persist even after resetting it?
Why does the value of this class variable persist even after resetting it?

Time:01-11

I have the following code, which is executed multiple times on different binary trees

class Solution:
    ans = []

    def getLonelyNodes(self, root: Optional[TreeNode]) -> List[int]:
        def helper(root):
            if root.left is None and root.right:
                self.ans.append(root.right.val)
                return helper(root.right)
            if root.left and root.right is None:
                self.ans.append(root.left.val)
                return helper(root.left)
            if root.left and root.right:
                return helper(root.left), helper(root.right)
            if root.left is None and root.right is None:
                return

        helper(root)
        ans = self.ans
        self.ans = []
        return ans

The problem is that even though I reset self.ans at the end, the values in ans persist for the next run (i.e. every run adds the previous answer to the current one).

I fixed the issue by moving self.ans = [] to above the helper function. But I don't understand why it's different to reset the answer at the beginning or end of the function call. How come it doesn't work to reset self.ans at the end, but it works at the beginning?

CodePudding user response:

self.ans is not the same as Solution.ans, even though it may sometimes seem like so.

self.ans references an instance attribute. Only when it is not found, Python tries to find it in class attributes. Assigning to self.ans does not affect Solution.ans, instead defines an instance attribute, which will be refferred to whenever you try to get value of self.ans.

class Foo:
    bar = []
    def reset(self):
        if self.bar is self.__class__.bar:
            print("same object")
        else:
            print("not same")
        self.bar = []
        if self.bar is self.__class__.bar:
            print("same object")
        else:
            print("not same")

foo = Foo()

foo.reset()
  • Related