Building a Python Counter Class with Locking Capability

Building a Python Counter Class with Locking Capability

class Counter:
    def __init__(self):
        self.count = 0
        self.locked = False

    def toggle_locked(self):
        self.locked = not self.locked

    def increment(self):  # Fixed the typo in the method name
        if self.locked:
            raise Exception("This counter is locked!")
        self.count += 1  # Fixed the variable name

    def decrement(self):  # Fixed the typo in the method name
        if self.locked:
            raise Exception("This counter is locked!")
        self.count -= 1  # Fixed the variable name

    def print_count(self):
        print(f"The current count is {self.count}")  # Added missing 'The'

# Example usage:
counter = Counter()
counter.print_count()  # Output: The current count is 0
counter.increment()
counter.print_count()  # Output: The current count is 1
counter.decrement()
counter.print_count()  # Output: The current count is 0
counter.toggle_locked()
counter.increment()  # Raises an exception: This counter is locked!

In this article, we'll explore how to create a Python class called Counter that allows you to keep track of a count and provides the ability to lock and unlock it to prevent accidental changes. We'll break down the code step by step and explain each part to help you understand how it works.

Code Explanation

pythonCopy codeclass Counter:
    def __init__(self):
        self.count = 0
        self.locked = False
  • The Counter class is defined, and it has two instance variables: count and locked.

  • count is initialized to 0, and locked is initially set to False.

pythonCopy code    def toggle_locked(self):
        self.locked = not self.locked
  • The toggle_locked method is used to toggle the locked state. When called, it switches the locked state between True and False. This feature allows you to lock the counter to prevent further modifications.
pythonCopy code    def increment(self):
        if self.locked:
            raise Exception("This counter is locked!")
        self.count += 1
  • The increment method increases the count by 1.

  • Before incrementing, it checks if the counter is locked (self.locked). If it's locked, it raises an exception to prevent unauthorized changes.

pythonCopy code    def decrement(self):
        if self.locked:
            raise Exception("This counter is locked!")
        self.count -= 1
  • The decrement method decreases the count by 1.

  • Similar to the increment method, it checks if the counter is locked before decrementing.

pythonCopy code    def print_count(self):
        print(f"The current count is {self.count}")
  • The print_count method simply prints the current count. It provides a formatted output to display the count.

Example Usage

The code includes an example of how to use the Counter class:

pythonCopy codecounter = Counter()
counter.print_count()  # Output: The current count is 0
counter.increment()
counter.print_count()  # Output: The current count is 1
counter.decrement()
counter.print_count()  # Output: The current count is 0
counter.toggle_locked()
counter.increment()  # Raises an exception: This counter is locked!
  • An instance of the Counter class, counter, is created.

  • The initial count is printed, incremented, and decremented with appropriate output.

  • The counter is then locked, and an attempt to increment it raises an exception, as expected.

In this article, we've introduced a Python class called Counter that demonstrates how to keep track of a count while offering the option to lock and unlock the counter to prevent unintended changes. This class can be a useful tool in various applications where controlled count management is necessary. You can further extend and customize the class to suit your specific needs.