Python OOP interview questions
25 questions interviewers ask on objects and classes, from first principles to the follow-ups. The first 3 model answers are free to read; Pro opens the rest.
Classes and objects
- What is the difference between a class and an instance?●
A class is a definition of a kind of object,
class Review:. An instance is one object created from it,review = Review("kettle", 5, "…"), with its own attributes.type(review)is<class '__main__.Review'>. - What is
self?●The conventional first parameter of an instance method: the object the method was called on.
review.is_positive()is the same call asReview.is_positive(review), and both giveTrue.selfis a convention, not a keyword, but every Python style guide uses it. - What does
__init__do? Is it the constructor?●It initialises a new object: Python creates the object, then calls
__init__on it with the arguments passed to the class. It is usually called the constructor. It must returnNone; its job is to set attributes such asself.rating = rating. - What happens if a method has no
selfparameter?●● - Where are an object's attributes stored?●●
- Why is setting a misspelt attribute dangerous?●●
- What is the difference between
==andisfor your own objects?●● - What are special methods (dunder methods)? Give examples.●●
- What is the difference between
__repr__and the default display?●● - "Everything in Python is an object." What does that mean in practice?●
Inheritance
- What is inheritance?●
- What does
super().__init__(...)do, and what happens without it?●● - How do you define a custom exception, and why subclass a built-in one?●●
Dataclasses
- What does
@dataclassgenerate?● - Does a dataclass check its type hints?●●
- Why can a dataclass field not have
[]as its default?●● - What does
frozen=Truedo, and when would you use it?●● - What is a decorator?●●
The estimator pattern
- What is the estimator pattern?●
- Why do learned attributes end in an underscore?●●
- Why does
fitreturnself?●● - What is the difference between a parameter and a hyperparameter?●●
- How does k-nearest neighbours regression predict?●●
- Why should
fitstore a copy of the data it is given?●● - Why is a model's error on its own training data a poor measure?●●