Implementing a Counter Class with Increment and Decrement in Python
We will create a simple counter class Counterthat supports increasing and decreasing the count. The class will contain an internal variable count to store the current count, and provide the increment and decrement methods to increase and decrease the count.
Example
class
Counter:
def
init
(
self
,
initial_count
=
0
)
:
self
.
count
=
initial_count
def
increment
(
self
,
value
=
1
)
:
self
.
count
=
value
def
decrement
(
self
,
value
=
1
)
:
self
.
count
=
value
def
get_count
(
self
)
:
return
self
.
count
Example usage
counter
=
Counter
(
10
)
counter.
increment
(
5
)
counter.
decrement
(
3
)
(
counter.
get_count
(
)
)
Code analysis:
__init__method is the class constructor, used to initialize the counter instance. It takes an optional parameterinitial_count, defaulting to 0, that sets the initial count.incrementmethod increases the count. It takes an optional parametervalue, defaulting to 1, which is the amount added each time.decrementmethod decreases the count. It also takes an optional parametervalue, defaulting to 1, which is the amount subtracted each time.get_countmethod returns the current count.
Output result:
12
Python3 Examples