Search code examples
pythonclassself

Why does removing 'self' cause an error when my input is valid?


I have a relatively basic question about classes and 'self', and although I know what they are used for after researching- I still don't quite understand some of the practical implementations.

My questions:

  1. I am getting 'self' is not defined for the last line of code. Why is this?

  2. I have seen in instances where within the function of post-order_traversal_iterative that I would do self.root, but in other cases it is just root. I know the purpose of class is so that we can reference variables and other things within the same class but in different functions, and that is where we would use self.root for example- is this right?

  3. Considering 2. I don't believe we need 'self' here at all. But when I take all the self's out, I get an unexpected argument for my input [1,None,2,3]

     class Treenode:
         def __init__(self,val=0, left=None, right=None):
             self.val = val
             self.left = left
             self.right = right
    
     class Solution:
         def post_order_traversal_iterative(self,root):
             stack = [root]
             output = []
             if not root:
                 return []
             while stack:
                 curr = stack.pop()
                 output.append(curr.val)
                 if curr.right:
                     stack.append(curr.left)
                 if curr.left:
                     stack.append(curr.right)
             return output
    
     x = Solution()
     print(x.post_order_traversal_iterative(self,[1, None, 2, 3]))
    

Solution

  • You don't mention self outside the class. Python uses this for you in the background in instance methods.

    You made an x, which allows you to call the instance method like this x.post_order_traversal_iterative([1, None, 2, 3])

    (Think of this like Solution.post_order_traversal_iterative(x, [1, None, 2, 3])