Classes & Objects · Question 20 · Hard
sell() uses self.stock -= 1 where stock starts as a class attribute, and the class attribute is changed later. What is printed?
class Shop:
stock = 10
def sell(self):
self.stock -= 1
a = Shop()
b = Shop()
a.sell()
a.sell()
Shop.stock = 50
print(a.stock, b.stock)
- 8 50
- 8 10
- 48 50
- 8 8
Answer and explanation
Answer: A. 8 50
Explanation: The first self.stock -= 1 reads 10 from the class and stores 9 as an instance attribute on a; the second makes it 8. b never got its own attribute, so it reads the class value, which is now 50.
Previous: total is a property with only a getter. What happens when the code tries to…
Practise classes & objects
Try a fresh set of classes & objects questions with an explanation after every answer, free and without signing up: Classes & Objects practice. Or sit a full placement mock test.
More classes & objects questions
- Every class in this diamond calls super().go(). What string does D().go() build?
- The Coin class defines both __str__ and __repr__. What is printed for the…
- total is a property with only a getter. What happens when the code tries to…
More python practice
Exceptions & Files · Built-ins & Standard Library · Variables, Types & Operators · Python Strings · Lists & Tuples · Dictionaries & Sets · Conditions & Loops · Functions & Scope
LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge