Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Implementing a Counter Class with Increment and Decrement in Python

Implementing a Counter Class with Increment and Decrement in Python

Document Object Reference Manual Python3 Examples

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

)

print

(

counter.

get_count

(

)

)

Code analysis:

Output result:

12

Document Object Reference Manual Python3 Examples