Top 10 Python Interview Questions Every Developer Should Master
This article compiles ten frequently asked Python interview questions, covering class inheritance, special methods like __call__, object creation with __new__, list and dictionary comprehensions, variable scope, swapping variables, default method handling via __getattr__, package exports, closures, and string concatenation performance, each illustrated with code examples and concise explanations.
Overview
Python is a widely used programming language, and with the rise of machine learning and cloud computing, demand for Python developers has increased. Below are ten common Python interview questions with code examples and explanations.
1. Class inheritance
class A(object):
def show(self):
print('base show')
class B(A):
def show(self):
print('derived show')
obj = B()
obj.show()To invoke the show method defined in class A, assign the class object to obj.__class__ and then call obj.show():
obj.__class__ = A
obj.show()This changes the method resolution order so that A.show is executed.
2. Method object (__call__)
Question: What code is required to make an instance callable?
class A(object):
def __init__(self, a, b):
self.__a = a
self.__b = b
def myprint(self):
print('a=', self.__a, 'b=', self.__b)
# missing __call__ implementation
a1 = A(10, 20)
a1.myprint()
a1(80) # raises TypeError without __call__Answer: Implement the __call__ method.
class A(object):
def __init__(self, a, b):
self.__a = a
self.__b = b
def myprint(self):
print('a=', self.__a, 'b=', self.__b)
def __call__(self, num):
print('call:', num + self.__a)3. __new__ and __init__
class B(object):
def fn(self):
print('B fn')
def __init__(self):
print('B INIT')
class A(object):
def fn(self):
print('A fn')
def __new__(cls, a):
print('NEW', a)
if a > 10:
return super(A, cls).__new__(cls)
return B()
def __init__(self, a):
print('INIT', a)
a1 = A(5)
a1.fn()
a2 = A(20)
a2.fn()Output:
NEW 5
B INIT
B fn
NEW 20
INIT 20
A fnThe __new__ method decides which object to return before initialization, useful for patterns such as singletons or factories.
4. List and dict generation
ls = [1, 2, 3, 4]
list1 = [i for i in ls if i > 2]
print(list1)
list2 = [i*2 for i in ls if i > 2]
print(list2)
dic1 = {x: x**2 for x in (2, 4, 6)}
print(dic1)
dic2 = {x: 'item' + str(x**2) for x in (2, 4, 6)}
print(dic2)
set1 = {x for x in 'hello world' if x not in 'low level'}
print(set1)Output:
[3, 4]
[6, 8]
{2: 4, 4: 16, 6: 36}
{2: 'item4', 4: 'item16', 6: 'item36'}
{'h', 'r', 'd'}5. Global and local variables
num = 9
def f1():
num = 20
def f2():
print(num)
f2()
f1()
f2()Output:
9
9Because num inside f1 is a local variable, the global num remains unchanged. To modify the global variable, declare it with global inside the function.
6. Swapping two variables
a = 8
b = 9
(a, b) = (b, a)7. Default method via __getattr__
class A(object):
def __init__(self, a, b):
self.a1 = a
self.b1 = b
print('init')
def mydefault(self, *args):
print('default:' + str(args[0]))
def __getattr__(self, name):
print('other fn:', name)
return self.mydefault
a1 = A(10, 20)
a1.fn1(33)
a1.fn2('hello')
a1.fn3(10)When an undefined method is called, __getattr__ returns mydefault, which handles the call.
8. Package management
To expose only mod1 and mod3 when using from demopack import *, define __all__ in __init__.py:
__all__ = ['mod1', 'mod3']9. Closure
def mulby(num):
def gn(val):
return num * val
return gn
zw = mulby(7)
print(zw(9)) # prints 6310. Performance of string concatenation
def strtest1(num):
s = 'first'
for i in range(num):
s += 'X'
return sExplanation: str objects are immutable; each concatenation creates a new string, leading to high memory usage and slower performance for large num. Using a list and ''.join() is more efficient.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
