Top 10 Essential Python Interview Questions Every Developer Should Know
This article compiles the ten most frequently asked Python interview questions, covering topics such as *args/**kwargs, object copying, garbage collection, lambda functions, singleton patterns, introspection, decorators, duck typing, classmethod/staticmethod, and metaclasses, each with clear explanations and code examples.
After many requests, we finally compiled a Python interview guide focusing on fundamental concepts, selecting the ten most common questions from numerous sources and providing concise answers.
1. What do *args and **kwargs mean?
*args represents variadic (positional) arguments and is gathered into a tuple; **kwargs represents keyword arguments and is gathered into a dict. When both are used, *args must appear before **kwargs in the function signature.
2. How can you copy an object in Python?
There are three main ways: (1) Assignment (=) creates a new reference, so changes affect both variables; (2) Shallow copy using copy.copy() creates a new container but references the original items; (3) Deep copy using copy.deepcopy() recursively copies all contained objects, so modifications are independent. Note that not all objects are copyable.
3. Briefly describe Python's garbage collection mechanism.
Python primarily uses reference counting: each object tracks how many references point to it, and when the count drops to zero the memory is released. It also employs a mark‑and‑sweep collector to break reference cycles and a generational collector that groups objects by age, collecting younger generations more frequently.
4. What is a lambda function and what are its benefits?
A lambda expression defines an anonymous, single‑line function in the form lambda parameters: expression. It returns the value of the expression, can be assigned to a variable, accepts any number of arguments (including defaults), but is limited to a single expression, making it handy for short, throw‑away functions.
5. How can you implement the singleton pattern in Python?
Several approaches exist:
1. Using __new__ to control instance creation:
class Singleton(object):
def __new__(cls, *args, **kw):
if not hasattr(cls, '_instance'):
orig = super(Singleton, cls)
cls._instance = orig.__new__(cls, *args, **kw)
return cls._instance
class MyClass(Singleton):
a = 12. Borg (shared‑state) pattern:
class Borg(object):
_state = {}
def __new__(cls, *args, **kw):
ob = super(Borg, cls).__new__(cls, *args, **kw)
ob.__dict__ = cls._state
return ob
class MyClass2(Borg):
a = 13. Decorator version:
def singleton(cls, *args, **kw):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls(*args, **kw)
return instances[cls]
return getinstance
@singleton
class MyClass:
...4. Import‑based singleton:
class My_Singleton(object):
def foo(self):
pass
my_singleton = My_Singleton()
# usage
from mysingleton import my_singleton
my_singleton.foo()6. What is Python introspection?
Introspection allows a program to examine objects at runtime, using functions such as type(), dir(), getattr(), hasattr(), and isinstance(). Example:
a = [1, 2, 3]
b = {'a': 1, 'b': 2, 'c': 3}
c = True
print(type(a), type(b), type(c))
print(isinstance(a, list)) # True7. Discuss Python decorators.
A decorator is a function that takes another function and extends its behavior without explicitly modifying it. Decorators are useful for logging, performance measurement, transaction handling, caching, permission checks, and other cross‑cutting concerns, allowing reusable code injection.
8. What is duck typing?
Duck typing focuses on an object's behavior rather than its explicit type; if an object walks and quacks like a duck, it can be used as a duck. Example:
class duck():
def walk(self):
print('I am duck, I can walk...')
def swim(self):
print('I am duck, I can swim...')
def call(self):
print('I am duck, I can call...')
duck1 = duck()
duck1.walk()
duck1.call()9. Explain @classmethod and @staticmethod. @classmethod defines a method that receives the class itself as the first argument ( cls) and can be called without creating an instance. @staticmethod defines a method that does not receive an implicit first argument; it behaves like a plain function placed inside the class namespace and can also be called without an instance.
10. Talk about metaclasses in Python.
Normally we define classes and instantiate them. A metaclass is a class of a class; it defines how classes are created. By specifying a metaclass, you can automatically modify a class at creation time, enabling advanced behaviors such as automatic attribute injection or registration.
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.
