In leetcode why am I getting the error "NameError: global name ‘climbStairs’ is not defined"? but works without ‘self’ and ‘object’?

  python

Here is the code:

class Solution(object):
    
    def climbStairs(self, n):
        if n in {0,1}:
            return 1
        else:
            return climbStairs(n-2) + climbStairs(n-1)

Full error message:

NameError: global name 'climbStairs' is not defined
    return climbStairs(n-2) + climbStairs(n-1)
Line 7 in climbStairs (Solution.py)
    ret = Solution().climbStairs(param_1)
Line 29 in _driver (Solution.py)
    _driver()
Line 39 in <module> (Solution.py)

I am thinking this has something to do with scope. Tried this in Spyder as well and same results. Why can’t I recursively call a method within a method in this example?

Also tried this code, and it works, but only when I remove the keywords ‘self’ and ‘object’ and removed the class definition, why is that?

Before (Error: TypeError: climbStairs() missing 1 required positional argument: ‘n’)

def climbStairs(self, n):
    if n in {0,1}:
        return 1
    else:
        return climbStairs(n-2) + climbStairs(n-1)
    
print(climbStairs(object, 8))

After (WORKS! without class def, ‘self’ and ‘object’ keywords):

def climbStairs(n):
    if n in {0,1}:
        return 1
    else:
        return climbStairs(n-2) + climbStairs(n-1)
    
print(climbStairs(8))

What does the class def, keyword ‘self’ and ‘object’ add to the code? Why do I need them?

Source: Python Questions

LEAVE A COMMENT