Implement a counter class in Python that supports addition and subtraction operations

Document 对象参考手册Python3 Examples

We will create a simple counter classCounter, which supports operations to increase and decrease the count value. This class will contain an internal variablecountto store the current count value, and provideincrementanddecrementmethods to increase and decrease the count value, respectively.

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:

  • __init__The method is the class constructor, used to initialize the counter instance. It accepts an optional parameterinitial_count, with a default value of 0, used to set the initial count value.
  • incrementThe method is used to increase the count value. It accepts an optional parametervalue, with a default value of 1, indicating the amount to increase each time.
  • decrementThe method is used to decrease the count value. It also accepts an optional parametervalue, with a default value of 1, indicating the amount to decrease each time.
  • get_countThe method is used to get the current count value.

Output result:

12

Document 对象参考手册Python3 Examples

Other extensions