Back to questions
JuniorTheoryCommon
What does the program print?
class Counter:
def __init__(self):
self.value = 0
def add(self, n):
self.value += n
a = Counter()
b = Counter()
a.add(5)
print(a.value, b.value)5 0
- Expecting
5 5, as if both objects shared onevalue: each callCounter()runs__init__for a new instance, andself.valuebelongs to that instance alone. - Expecting a
TypeErrorbecauseaddhas two parameters and gets one argument: Python passes the instance asselfitself, soa.add(5)fills both.
- What would
b.add(2)followed byprint(a.value, b.value)print? - How does
selfinsideaddknow which object to change?