【发布时间】:2020-05-10 20:18:00
【问题描述】:
我正在尝试在 OOP 中创建一个停车场。我想检查我的字典中是否已经有任何键。 例如,我不想在我的字典中使用相同的“车牌号”。
我正在使用命令:
if plate in p1.carsAndEnterTime:
print("This plate number already exists in the system")
plate = input("Please enter the plate number:\n")
但它没有找到任何密钥。
这是我的完整代码:
class Cars:
def __init__(self, phone, car_type, plate):
self.__phone = phone
self.__car_type = car_type
self.__plate = plate
def __repr__(self):
return f"{self.__plate}, {self.__phone}, {self.__car_type}"
def __str__(self):
return f"{self.__plate}, {self.__phone}, {self.__car_type}"
class ParkingLot:
def __init__(self, name, capacity=1):
''' return a ParkingLot object with name "name" '''
self.name = name
self.capacity = capacity
self.earnings = 0
self.rate = 15
self.carsAndEnterTime = {}
def SetCapacity(self, newCap):
''' change the capacity from the default 1 '''
if newCap < 1:
raise RuntimeError("Error: parking lot size cannot be less than 1")
self.capacity = newCap
def GetCapacity(self):
''' return parking lot capacity '''
return self.capacity
def GetEarnings(self):
''' return how much much parking has made '''
return self.earnings
def VehicleEnters(self, vehicle):
''' vehicle enters parking lot'''
# put car and its enter time in a dictionary
self.carsAndEnterTime[vehicle] = datetime.datetime.now()
if self.capacity == 0:
raise RuntimeError("Error: Parking lot full!")
self.capacity -= 1
def SetSecondlyRate(self, rate=20):
self.rate = rate
def VehicleLeaves(self, vehicle):
''' vehicle leaves parking lot. when it leaves, charges money '''
secondsDiff = datetime.datetime.now() - self.carsAndEnterTime[vehicle]
hour_roundup = math.ceil(secondsDiff.seconds / 3600)
self.earnings += self.rate * hour_roundup
# after earned money, delete vehicle from dictionary
del self.carsAndEnterTime[vehicle]
self.capacity += 1
当我执行以下操作时:
>>> p1 = ParkingLot(p1,2)
>>> plate = 12345
>>> car_type = "Public"
>>> phone = "05555555"
>>> c = c1 = Cars(plate, car_type, phone)
当我尝试检查 dict 中的 palte 是否 但它的忽略,虽然palte存在dict。
if plate in p1.carsAndEnterTime:
print("This plate number already exists in the system")
plate = input("Please enter the plate number:\n")
例如我打印我的字典: 你可以看到 12345 在我的字典中找到了。
>>>print(p1.carsAndEnterTime)
{12345, 55555, p: datetime.datetime(2020, 5, 10, 23, 0, 36, 557859), 12345, 5555, p: datetime.datetime(2020, 5, 10, 23, 0, 44, 568150)}
我做错了什么,我该如何解决?
【问题讨论】:
-
字典中的键不是整数,而是
Cars的实例。 12345 不是Cars,也不是该字典中的键。 -
这也不是minimal reproducible example 代码。我们应该能够运行并得到相同的结果
标签: python-3.x class dictionary