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)
- 4 6 6
- 6 6 4
- 4 6 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
- Wheels is a class attribute, shared by all cars.
- c.wheels = 6 creates an instance attribute on c only.
- Car.wheels and Car('Kia').wheels still read the class value 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?
- Method overriding
- Encapsulation
- Name mangling
- 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
- Overriding means a subclass defines a method with the same name as one in its parent.
- The subclass version is used when it is called on a subclass object.
- 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"))
- Book: Gita
- <__main__.Book object>
- Book(Gita)
- Gita
Answer: A. Book: Gita
Explanation
print calls str(), which uses the class's __str__ method.
Step-by-step solution
print(obj) calls str(obj), which uses the class's __str__ method.__str__ returns "Book: " + self.title, which is "Book: Gita".- 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?
- It receives neither the instance nor the class automatically as its first argument
- It receives the class as its first argument
- It can be called only on the class, never on an instance
- 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
- A regular method gets the instance as self automatically.
- A class method gets the class as cls.
- A static method gets neither, so it is just a function in the class namespace.
- 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)
- read-only 500
- read-only 100
- 500
- 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
- balance is a read-only property.
- Assigning raises AttributeError.
- 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)])
- 2 True
- 3 True
- TypeError
- 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
Pt(1) and Pt(1) have equal hashes and are equal, so the set keeps one of them.Pt(2) has a different hash and value, so it is a second item in the set.len of the set is 2.Pt(3) in [Pt(3)] uses __eq__ on the two objects, which is True.- 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)
- 0
- 12
- TypeError
- 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
sum starts from 0: 0 + Money(5).int cannot add Money, so Python calls Money.__radd__.- That gives Money(5); then Money(5)+Money(7) = Money(12).
- 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)
- 0
- -273
- -500
- 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
- Assigning t.c = -500 calls the setter.
- The setter stores max of -500 and -273, which is -273.
- Reading t.c calls the getter, which returns -273.
- 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)}))
- TypeError: unhashable type
- 2 is printed
- AttributeError is raised
- 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
- Defining eq without hash sets hash to None in Python 3.
- Instances of P are therefore unhashable.
- Putting them in a set calls hash, which raises TypeError.
- 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__"))
- True
- False
- no y True
- 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
__slots__ allows only x as an attribute name.- Setting
a.y raises AttributeError, so no y is printed. - With
__slots__ there is no per-instance __dict__, so hasattr returns False. - 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 →