class Tony_Counter():
def __init__(self):
self.counter: int = 0
def increment(self):
self.counter += 1
def __call__(self):
self.increment()
1. Create Tony_Counter
Class
Instance attribute
.counter
defaulted to zero.Instance method
increment()
increases.counter
attribute by 1Magic Method
__call__()
calls instance methodincrement()
:In other words, when an instance calls itself with
()
, theinstance.__call__()
will be called:- In this case incrementing
.counter
by 1 each time.
- In this case incrementing
= Tony_Counter()
ctr print(ctr.counter)
0
ctr.increment()print(ctr.counter)
1
ctr.increment()print(ctr.counter)
2