Python Interview Questions That Can Stump You! 🚀 #Python #InterviewPrep #Tech

preview_player
Показать описание
Here are 5 tricky Python interview questions with answers:

1️⃣ What are Python’s special (dunder) methods?

Dunder (double underscore) methods are magic methods in Python used to define object behavior.

Examples: __init__, __str__, __len__, __eq__, __call__, etc.

class Demo:
def __init__(self, value):

def __str__(self):

obj = Demo(10)
print(obj) # Calls __str__, output: Demo object with value 10

2️⃣ How does Python handle default mutable arguments in functions?

Default mutable arguments (like lists or dictionaries) can lead to unexpected behavior.

The same object is reused across multiple function calls.

def add_item(item, lst=[]):
return lst

print(add_item(1)) # [1]
print(add_item(2)) # [1, 2] (unexpected behavior!)

# Correct way:
def add_item_fixed(item, lst=None):
if lst is None:
lst = []
return lst

3️⃣ What is the difference between @staticmethod, @classmethod, and instance methods?

Instance methods (self) → Act on instance data.

class Demo:
def instance_method(self):
return "Instance method called", self

@classmethod
def class_method(cls):
return "Class method called", cls

@staticmethod
def static_method():
return "Static method called"

obj = Demo()

4️⃣ How does Python implement method resolution order (MRO)?

Python follows the C3 Linearization (MRO) algorithm.

Uses Depth-First Search (DFS) + Left-to-Right Order.

Can check MRO using Class.__mro__ or help(Class).

class A: pass
class B(A): pass
class C(A): pass
class D(B, C): pass

print(D.__mro__) # (vclass 'D'V, vclass 'B'V, vclass 'C'V, vclass 'A'V, vclass 'object'V)

5️⃣ What is the difference between yield and return in Python?

return exits the function and returns a value.

yield pauses execution and returns a generator.

def simple_generator():
yield 1
yield 2
yield 3

gen = simple_generator()
print(next(gen)) # 1
print(next(gen)) # 2
print(next(gen)) # 3
Want more Python interview tricks? Follow for more! 🚀

#Python #PythonInterview #DunderMethods #PythonFunctions #MRO #YieldVsReturn #PythonCoding
Рекомендации по теме
visit shbcf.ru