Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create a simple lock and key function in Python

class Lock:
 
   def __init__(self):
        self.key_code = "1234"  # Change this to your desired key code
        self.is_locked = True

    def lock(self):
        self.is_locked = True

    def unlock(self, entered_code):
        if entered_code == self.key_code:
            self.is_locked = False
        else:
            print("Incorrect key code. Lock remains locked.")

    def is_locked(self):
        return self.is_locked


def main():
    my_lock = Lock()

    print("The lock is currently locked.")
    while my_lock.is_locked():
        entered code = input("Enter the key code: ")
        my_lock.unlock(entered code)

    print("The lock is now unlocked.")


if __name__ == "__main__":
    main()

I wrote this code but it is showing an

Type Error: 'bool' object is not callable
The lock is currently locked.

I have been trying to create a lock mechanism but it is showing an type error. I had tried many ways but I still couldn’t solve it.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

he issue is due to the naming conflict between the is_locked attribute and the is_locked() method. Both have the same name, and that’s causing the error. To fix it, let’s rename the method to get_lock_status() instead of is_locked(). Here’s the corrected code:

class Lock:
def init(self):
self.key_code = "1234"
self.is_locked = True

          def lock(self):
             self.is_locked  = True

def unlock(self, entered_code):
    if entered_code == self.key_code:
        self.is_locked = False
    else:
        print("Incorrect key code. Lock remains locked.")

def get_lock_status(self):
    return self.is_locked


        def main():
               my_lock = Lock()

print("The lock is currently locked.")
while my_lock.get_lock_status():
    entered_code = input("Enter the key code: ")
    my_lock.unlock(entered code)

print("The lock is now unlocked.")
    if __name__ == "__main__":
      main()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading