OOP & Dunder Methods Questions with Answers

32 practice questions on OOP & Dunder Methods (Python) with answers and step-by-step solutions. Try 10 samples below, then practise all 32 free in the AptiNest app.

Sample questions

Question 1Easy

What is the output?

class Car:
    wheels = 4
    def __init__(self, brand):
        self.brand = brand

c = Car("Tata")
c.wheels = 6
print(Car.wheels, c.wheels, Car("Kia").wheels)
  1. 4 6 6
  2. 6 6 4
  3. 4 6 4
  4. 6 6 6

Answer: C. 4 6 4

Explanation

c.wheels = 6 creates an instance attribute that hides the class attribute only for c; the class and other instances still see 4.

Step-by-step solution

  1. Wheels is a class attribute, shared by all cars.
  2. c.wheels = 6 creates an instance attribute on c only.
  3. Car.wheels and Car('Kia').wheels still read the class value 4.
  4. The output is 4 6 4.

Why the other options are wrong

  • A. Setting c.wheels does not change the class attribute, so Car.wheels stays 4 and c.wheels is 6.
  • B. c.wheels is 6 because the instance attribute hides the class value.
  • D. Only c has the instance value 6; the class and other instances stay at 4.

Tip: Assigning through an instance creates an instance attribute; it does not change the class attribute.

Question 2Easy

Which feature lets a subclass provide its own version of a method already defined in the parent class?

  1. Method overriding
  2. Encapsulation
  3. Name mangling
  4. Method overloading by parameter types

Answer: A. Method overriding

Explanation

Overriding replaces the inherited method; Python does not support overloading by parameter signature (the last definition wins).

Step-by-step solution

  1. Overriding means a subclass defines a method with the same name as one in its parent.
  2. The subclass version is used when it is called on a subclass object.
  3. So the correct answer is option A.

Why the other options are wrong

  • B. Encapsulation is about hiding data inside a class, not replacing a parent method.
  • C. Name mangling changes names of private attributes; it does not replace methods.
  • D. Python does not overload methods by parameter types; the last definition wins.

Tip: Overriding replaces a parent method in a subclass; Python has no overloading by parameter type.

Question 3Easy

What is the output?

class Book:
    def __init__(self, title):
        self.title = title
    def __str__(self):
        return "Book: " + self.title

print(Book("Gita"))
  1. Book: Gita
  2. <__main__.Book object>
  3. Book(Gita)
  4. Gita

Answer: A. Book: Gita

Explanation

print calls str(), which uses the class's __str__ method.

Step-by-step solution

  1. print(obj) calls str(obj), which uses the class's __str__ method.
  2. __str__ returns "Book: " + self.title, which is "Book: Gita".
  3. So the output is Book: Gita, which is A.

Why the other options are wrong

  • B. The default object representation is used only when __str__ is missing.
  • C. The text is "Book: " followed by the title, not Book(Gita).
  • D. The method adds the "Book: " prefix, so the output is not just Gita.

Tip: print uses __str__; repr() uses __repr__.

Question 4Easy

What does @staticmethod change about a method defined in a class?

  1. It receives neither the instance nor the class automatically as its first argument
  2. It receives the class as its first argument
  3. It can be called only on the class, never on an instance
  4. It makes the method run only once per class

Answer: A. It receives neither the instance nor the class automatically as its first argument

Explanation

A static method is a plain function placed in the class namespace; it can be called on the class or an instance and gets no implicit self or cls.

Step-by-step solution

  1. A regular method gets the instance as self automatically.
  2. A class method gets the class as cls.
  3. A static method gets neither, so it is just a function in the class namespace.
  4. So the answer is option A.

Why the other options are wrong

  • B. Receiving the class as the first argument is what a classmethod does.
  • C. A staticmethod can be called on the class or an instance.
  • D. A staticmethod does not limit calls to once; it is an ordinary function.

Tip: Staticmethod gets no implicit first argument; classmethod gets cls; a normal method gets self.

Question 5Medium

What is the output?

class Account:
    def __init__(self):
        self._balance = 100
    @property
    def balance(self):
        return self._balance

a = Account()
try:
    a.balance = 500
except AttributeError:
    print("read-only", a.balance)
  1. read-only 500
  2. read-only 100
  3. 500
  4. 100

Answer: B. read-only 100

Explanation

A property with only a getter has no setter, so assignment raises AttributeError and the value stays 100.

Step-by-step solution

  1. balance is a read-only property.
  2. Assigning raises AttributeError.
  3. The except prints read-only and the unchanged balance 100.

Why the other options are wrong

  • A. The assignment failed, so balance stays 100.
  • C. The error is caught first, so 500 never prints.
  • D. The except block prints 'read-only' too.

Tip: No setter = read-only.

Question 6Medium

What is the output?

class Pt:
    def __init__(self, x):
        self.x = x
    def __eq__(self, o):
        return self.x == o.x
    def __hash__(self):
        return hash(self.x)

print(len({Pt(1), Pt(1), Pt(2)}), Pt(3) in [Pt(3)])
  1. 2 True
  2. 3 True
  3. TypeError
  4. 2 False

Answer: A. 2 True

Explanation

With matching __eq__ and __hash__, equal points collapse into one set entry, and list membership uses __eq__.

Step-by-step solution

  1. Pt(1) and Pt(1) have equal hashes and are equal, so the set keeps one of them.
  2. Pt(2) has a different hash and value, so it is a second item in the set.
  3. len of the set is 2.
  4. Pt(3) in [Pt(3)] uses __eq__ on the two objects, which is True.
  5. The output is 2 True, which is A.

Why the other options are wrong

  • B. The two Pt(1) objects are equal, so the set has 2 items, not 3.
  • C. Both __eq__ and __hash__ are defined, so no TypeError happens.
  • D. The membership test is True because __eq__ returns True for equal x values.

Tip: Define __eq__ and __hash__ together so equal objects are treated as one set item.

Question 7Medium

What is the output?

class Money:
    def __init__(self, v):
        self.v = v
    def __add__(self, other):
        return Money(self.v + (other.v if isinstance(other, Money) else other))
    def __radd__(self, other):
        return self.__add__(other)

print(sum([Money(5), Money(7)]).v)
  1. 0
  2. 12
  3. TypeError
  4. 7

Answer: B. 12

Explanation

sum starts from 0, so the first step is 0 + Money(5); int.__add__ returns NotImplemented and Python calls Money.__radd__, giving Money(5), then Money(12).

Step-by-step solution

  1. sum starts from 0: 0 + Money(5).
  2. int cannot add Money, so Python calls Money.__radd__.
  3. That gives Money(5); then Money(5)+Money(7) = Money(12).
  4. Print .v: 12.

Why the other options are wrong

  • A. Both items are added.
  • C. __radd__ makes 0 + Money work.
  • D. Both values are included.

Tip: Define __radd__ to use sum().

Question 8Medium

What is the output?

class Temp:
    def __init__(self):
        self._c = 0
    @property
    def c(self):
        return self._c
    @c.setter
    def c(self, v):
        self._c = max(v, -273)

t = Temp()
t.c = -500
print(t.c)
  1. 0
  2. -273
  3. -500
  4. AttributeError

Answer: B. -273

Explanation

Assigning to t.c calls the setter, which clamps the value to -273; reading t.c calls the getter.

Step-by-step solution

  1. Assigning t.c = -500 calls the setter.
  2. The setter stores max of -500 and -273, which is -273.
  3. Reading t.c calls the getter, which returns -273.
  4. The output is -273.

Why the other options are wrong

  • A. The setter clamps the value, so it is not reset to 0.
  • C. The stored value is clamped to -273, so -500 is not kept.
  • D. The property is defined correctly, so no AttributeError is raised.

Tip: A property setter runs on assignment, so it can validate or clamp the value.

Question 9Hard

What happens when this code runs?

class P:
    def __init__(self, v):
        self.v = v
    def __eq__(self, other):
        return self.v == other.v

print(len({P(1), P(1)}))
  1. TypeError: unhashable type
  2. 2 is printed
  3. AttributeError is raised
  4. 1 is printed

Answer: A. TypeError: unhashable type

Explanation

Defining __eq__ without __hash__ sets __hash__ to None, making instances unhashable, so they cannot be put in a set.

Step-by-step solution

  1. Defining eq without hash sets hash to None in Python 3.
  2. Instances of P are therefore unhashable.
  3. Putting them in a set calls hash, which raises TypeError.
  4. So the output is a TypeError about an unhashable type.

Why the other options are wrong

  • B. The set cannot be built, so no length is printed.
  • C. The error is TypeError from hashing, not AttributeError.
  • D. Both P(1) objects are rejected before the length is taken, so 1 is not printed.

Tip: If a class defines eq, also define hash when its objects must go in sets or dict keys.

Question 10Hard

What is the output?

class A:
    __slots__ = ("x",)

a = A()
a.x = 1
try:
    a.y = 2
except AttributeError:
    print("no y", end=" ")
print(hasattr(a, "__dict__"))
  1. True
  2. False
  3. no y True
  4. no y False

Answer: D. no y False

Explanation

__slots__ restricts instances to the named attributes and removes the per-instance __dict__, so setting y fails and hasattr(a, "__dict__") is False.

Step-by-step solution

  1. __slots__ allows only x as an attribute name.
  2. Setting a.y raises AttributeError, so no y is printed.
  3. With __slots__ there is no per-instance __dict__, so hasattr returns False.
  4. The output is no y False.

Why the other options are wrong

  • A. The instance has no __dict__, so hasattr is False, not True.
  • B. The except block prints no y before the hasattr line runs.
  • C. hasattr(a, '__dict__') is False, not True.

Tip: __slots__ fixes the attribute names and saves memory by removing the per-instance __dict__.

Practise all 32 questions free

The full question bank with timed practice, progress tracking and Vidya, your AI tutor. Free, no ads.

Open this topic in the app →

Related topics

See all Python topics · All topics