Top 10 Must‑Know Python Interview Questions and Answers
This article compiles ten of the most frequently asked Python interview questions, covering topics such as *args and **kwargs, object copying methods, garbage collection, lambda functions, singleton patterns, introspection, decorators, duck typing, classmethod versus staticmethod, and metaclasses, each accompanied by clear explanations and code examples.
1. What do *args and **kwargs mean?
*args collects variable positional arguments into a tuple; **kwargs collects variable keyword arguments into a dict. *args must appear before **kwargs in a function definition.
2. How to copy an object in Python?
Three ways: assignment (=) creates a new reference; shallow copy via copy.copy() copies the container but references inner objects; deep copy via copy.deepcopy() recursively copies all nested objects. Not all objects are copyable.
3. Briefly describe Python's garbage collection mechanism.
Python uses reference counting as the primary garbage collector, supplemented by mark‑and‑sweep and generational collection. When an object's reference count drops to zero it is deallocated. Cyclic references are handled by the mark‑and‑sweep collector. Objects are grouped into three generations; younger generations are collected more frequently.
4. What is a lambda function and its benefits?
A lambda is an anonymous single‑expression function defined with the syntax lambda parameters: expression. It returns the expression value, can be assigned to a variable, and accepts any number of arguments but only a single expression.
5. How to implement the Singleton pattern in Python?
Several approaches exist: overriding __new__ to store a single instance, using a shared‑state (Borg) class, a decorator that caches instances, or creating a module‑level instance and importing it. Example snippets:
class Singleton(object):
def __new__(cls, *args, **kw):
if not hasattr(cls, '_instance'):
cls._instance = super(Singleton, cls).__new__(cls, *args, **kw)
return cls._instance
class MyClass(Singleton):
a = 1 class Borg(object):
_state = {}
def __new__(cls, *args, **kw):
obj = super(Borg, cls).__new__(cls, *args, **kw)
obj.__dict__ = cls._state
return obj 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:
pass6. What is Python introspection?
Introspection allows a program to examine the type or attributes of objects at runtime using functions like type(), dir(), getattr(), hasattr(), 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))7. Explain Python decorators.
Decorators are functions that wrap another function to extend its behavior without modifying its code. They return a new function object and are useful for logging, timing, caching, authentication, and other cross‑cutting concerns.
8. What is duck typing?
Duck typing focuses on an object's behavior rather than its explicit type; if an object walks like a duck 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. Difference between @classmethod and @staticmethod.
@classmethod receives the class as the first argument ( cls) and can access class attributes; it can be called without creating an instance. @staticmethod does not receive any implicit first argument and behaves like a plain function placed inside a class.
10. What are metaclasses in Python?
Metaclasses are classes of classes; they define how classes are created. By customizing a metaclass you can automatically modify class definitions during creation, enabling automatic injection of attributes or methods.
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.
