Fundamentals 8 min read

Top 10 Python Interview Questions Every Developer Should Master

Explore ten essential Python interview questions covering class inheritance, method objects, __new__ vs __init__, list and dict comprehensions, variable scope, tuple swapping, dynamic attribute handling, package imports, closures, and string performance, each with code examples and clear explanations to boost your interview readiness.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Top 10 Python Interview Questions Every Developer Should Master

1. Class Inheritance

Given the following code, the show method of class A can be called by reassigning the instance's __class__ attribute to A before invoking show.

class A(object):
    def show(self):
        print('base show')

class B(A):
    def show(self):
        print('derived show')

obj = B()
obj.show()          # prints: derived show
obj.__class__ = A
obj.show()          # prints: base show

2. Method Objects

To allow an instance to be called like a function, 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)

a1 = A(10, 20)
a1.myprint()        # prints: a= 10 b= 20
a1(80)             # prints: call: 90

3. __new__ and __init__

The output demonstrates how __new__ can decide which object to return before initialization, which is useful for patterns such as singletons or factories.

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()            # prints: B INIT, B fn
a2 = A(20)
a2.fn()            # prints: INIT 20, A fn

4. List and Dict Comprehensions

The code produces filtered and transformed collections using comprehensions.

ls = [1, 2, 3, 4]
list1 = [i for i in ls if i > 2]
print(list1)        # [3, 4]
list2 = [i*2 for i in ls if i > 2]
print(list2)        # [6, 8]

dic1 = {x: x**2 for x in (2, 4, 6)}
print(dic1)         # {2: 4, 4: 16, 6: 36}

dic2 = {x: 'item' + str(x**2) for x in (2, 4, 6)}
print(dic2)         # {2: 'item4', 4: 'item16', 6: 'item36'}

set1 = {x for x in 'hello world' if x not in 'low level'}
print(set1)        # {'h', 'r', 'd'}

5. Global and Local Variables

Without the global keyword, assignments inside a function create a new local variable, leaving the module‑level variable unchanged.

num = 9

def f1():
    num = 20   # local copy

def f2():
    print(num)

f2()   # prints 9
f1()
f2()   # prints 9 again

# Using global to modify the outer variable

def f1():
    global num
    num = 20

def f2():
    print(num)

f2()   # 9
f1()
f2()   # 20

6. Swapping Two Variables

A single line can exchange the values of two variables using tuple unpacking.

a = 8
b = 9
(a, b) = (b, a)   # a becomes 9, b becomes 8

7. Default Method via __getattr__

Implement __getattr__ to redirect undefined method calls to a default handler.

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)          # prints: other fn: fn1  then default:33
a1.fn2('hello')     # prints: other fn: fn2  then default:hello
a1.fn3(10)          # prints: other fn: fn3  then default:10

8. Package Import Control

Define __all__ in __init__.py to limit which modules are exported when using from demopack import *.

__all__ = ['mod1', 'mod3']

9. Closure Example

A function that returns another function capturing a variable creates a closure.

def mulby(num):
    def gn(val):
        return num * val
    return gn

zw = mulby(7)
print(zw(9))   # prints 63

10. String Concatenation Performance

Repeated string concatenation inside a loop is slow because strings are immutable; each iteration creates a new string object, leading to high memory usage. Using a list and ''.join() is more efficient.

def strtest1(num):
    s = ['first']
    for i in range(num):
        s.append('X')
    return ''.join(s)
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

interviewOOP
MaGe Linux Operations
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.