📅  最后修改于: 2023-12-03 15:28:45.067000             🧑  作者: Mango
这道题目要求我们实现一个门的类,门有两种状态:开和关。门可以被打开和关闭,但是如果门已经处于想要走的状态,那么什么都不会发生。门还有一个状态,用于判断是否被锁住,因此门可以处于四种不同的状态之一。
我们可以实现一个门的类,该类有一个状态属性,表示门的状态以及一些方法。
class Door:
"""Represents a door."""
def __init__(self):
"""Initializes the door as closed and unlocked."""
self._is_closed = True
self._is_locked = False
def open(self):
"""Opens the door."""
if not self._is_locked and self._is_closed:
self._is_closed = False
print("Door is now open.")
elif self._is_locked:
print("Cannot open door. It is locked.")
else:
print("Door is already open.")
def close(self):
"""Closes the door."""
if self._is_closed:
print("Door is already closed.")
else:
self._is_closed = True
print("Door is now closed.")
def lock(self):
"""Locks the door."""
if self._is_locked:
print("Door is already locked.")
else:
self._is_locked = True
print("Door is now locked.")
def unlock(self):
"""Unlocks the door."""
if not self._is_locked:
print("Door is already unlocked.")
else:
self._is_locked = False
print("Door is now unlocked.")
我们可以使用门的类来创建门实例,并对门进行打开、关闭、锁定和解锁操作。
# Create a door instance
door = Door()
# Open the door
door.open() # Output: Door is now open.
# Try to open the door when it is already open
door.open() # Output: Door is already open.
# Close the door
door.close() # Output: Door is now closed.
# Try to close the door when it is already closed
door.close() # Output: Door is already closed.
# Lock the door
door.lock() # Output: Door is now locked.
# Try to open the door when it is locked
door.open() # Output: Cannot open door. It is locked.
# Unlock the door
door.unlock() # Output: Door is now unlocked.
# Open the door after unlocking it
door.open() # Output: Door is now open.
如上所示,在门的实例上直接使用方法,可以执行开门、关门、锁门、打开门等方法,然后我们可以按照门的状态进行操作。