📜  门| GATE CS 2018 |问题 5(1)

📅  最后修改于: 2023-12-03 14:58:20.279000             🧑  作者: Mango

门 | GATE CS 2018 |问题 5

简介

本题是GATE CS 2018考试中的编程问题,主要考察面向对象程序设计的能力。目标是实现一个门类,其中包括锁和钥匙两个子类,以及它们的相关方法和属性。

题目描述

实现一个门类,包括以下方法和属性:

属性
  • isopen:一个布尔值,表示门是否打开
  • doorlock:门上的锁对象
方法
  • open():如果门没有被锁上,则把门打开
  • close():把门关闭
  • lock(key):如果门是关闭的,使用给定的key锁住门
  • unlock(key):如果门被锁上且当前钥匙与锁对应,则使用给定的key打开门

实现一个锁类,包括以下方法和属性:

属性
  • key:锁对应的钥匙
方法
  • lockDoor(door):锁住给定的门
  • unlockDoor(door, key):打开给定门上的锁,使用给定的钥匙

请注意,有多个门和钥匙,每个钥匙只匹配其中一个门才能打开。

案例
class Key:
    def __init__(self, key_id):
        self.key_id = key_id

class Lock:
    def __init__(self, lock_id):
        self.lock_id = lock_id
        self.is_locked = False
        self.key = None

    def lock_door(self, door, key):
        if self.is_locked:
            raise ValueError("This lock is already locked.")

        self.is_locked = True
        self.key = key
        door.door_lock = self
        return "Lock successful."

    def unlock_door(self, door, key):
        if not self.is_locked:
            raise ValueError("This lock is not locked.")

        if self.key != key:
            raise ValueError("The key is incorrect.")

        self.is_locked = False
        self.key = None
        door.door_lock = None
        return "Unlock successful."

class Door:
    def __init__(self, door_id):
        self.door_id = door_id
        self.is_open = False
        self.door_lock = None

    def open_door(self):
        if self.door_lock and self.door_lock.is_locked:
            raise ValueError("The door is locked.")
        self.is_open = True
        return "Door is open."

    def close_door(self):
        self.is_open = False
        return "Door is closed."

    def lock_door(self, key):
        if self.is_open:
            raise ValueError("The door is open.")
        if not key:
            raise ValueError("Please input the key.")
        if self.door_lock and self.door_lock.is_locked:
            raise ValueError("The door lock is already locked.")

        lock_ = Lock(str(self.door_id))
        lock_.lock_door(self, key)
        return "Door lock success."

    def unlock_door(self, key):
        if not self.door_lock:
            raise ValueError("The door lock not exists.")
        return self.door_lock.unlock_door(self, key)

key1 = Key("X23")
key2 = Key("Z34")
door1 = Door("D1")
door2 = Door("D2")
lock1 = Lock("L1")
lock2 = Lock("L2")

door1.lock_door(key1)
lock1.lock_door(door2, key2)
总结

此题考察面向对象编程,涵盖了Python中创建类和实例,继承和多态的概念,需要针对具体的对象设计相关的属性和方法,还需要注意抛出异常及其合理使用。该题的解法需要对面向对象编程有一定的掌握,同时要具备扎实的编程基础知识。