Member-only story
10 Advanced Python Interview Questions
Nail your next interview

With Python becoming more and more popular lately, many of you are probably undergoing technical interviews dealing with Python right now. In this post, I will list ten advanced Python interview questions and answers.
These can be confusing and are directed at mid-level developers, who need an excellent understanding of Python as a language and how it works under the hood.
What Are Nolocal and Global Keywords Used For?
These two keywords are used to change the scope of a previously declared variable. nolocal
is often used when you need to access a variable in a nested function:
def func1():
x = 5
def func2():
nolocal x
print(x)
func2()
global
is a more straightforward instruction. It makes a previously declared variable global. For example, consider this code:
x = 5
def func1():
print(x)
func1()
> 5
Since x
is declared before the function call, func1
can access it. However, if you try to change it:
x = 5
def func2():
x += 3
func2()
> UnboundLocalError: local variable 'c' referenced before assignment
To make it work, we need to indicate that by x
we mean the global variable x
:
x = 5
def func2():
global x
x += 3
func2()
What Is the Difference Between Classmethod and Staticmethod?
Both of them define a class method that can be called without instantiating an object of the class. The only difference is in their signature:
class A:
@staticmethod
def func1():
pass
@classmethod
def func2(cls):
pass
As you can see, the classmethod
accepts an implicit argument cls
, which will be set to the class A
itself. One common use case for classmethod
is creating alternative inheritable constructors.