Skip to content
Advertisement

Why Does Python Method Needs a `self` pointer for Recursion to Work?

I’m new to Python and want to use it for LeetCode. I was doing a recursion problem and realized that I have to use self. pointer in order for the recursion to work. Here is my initial code:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head or not head.next:
            return head
        
        p = reverseList(head.next)
        head.next.next = head
        head.next = None
        
        return p

However, this would give me an error:

NameError: name 'reverseList' is not defined

I had to add a self. before reverseList() in order for it to work. I’m curious that why Python is acting like this way? Java and C++ are all fine with recursion without a this pointer. It’s a little bit strange, since if I declare my function outside of a class, it wouldn’t need a self pointer for recursion to work.

Advertisement

Answer

This doesn’t really have anything to do with recursion per se, but with where the name reverseList is defined.

Inside the function, free variables (i.e., variables not defined the function itself) are looked up in the closest enclosing scope. The class statement, however, does not define a new scope, so reverseList must be defined in the global scope if it is to be used. But you don’t want anything from the global scope; you want to call the instance method. To do so, you must access it from the same instance that made the top-level call, i.e., self.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement