一辆车开到停车场,看到一个显示屏,屏幕上显示剩余车位数, 并随机显示一个可以的车位号?用面向对象方法实现编程。
本人实现方法:
import random
class Car(object):
sum_carport = [1, 2, 3]
carts = []
def __init__(self, num):
self.name = num
print('剩余空车位', self.sum_carport)
def look_for_parking(self):
cart_port_dict = {}
if 0 < len(self.sum_carport):
park = random.choice(self.sum_carport)
cart_port_dict[self.name] = park
Car.carts.append(cart_port_dict)
self.sum_carport.remove(park)
print('%s占用车位%s' % (self.name, park))
else:
print('%s无车位' % self.name)
print('车位都被占用啦', Car.carts)
cart1 = Car('拖拉机')
cart1.look_for_parking()
print('------------------------')
cart2 = Car('夏利')
cart2.look_for_parking()
print('=========================')
cart3 = Car('吉普')
cart3.look_for_parking()
print('=========================')
cart4 = Car('毛驴')
cart4.look_for_parking()
结果:
剩余空车位 [1, 2, 3]
剩余空车位 [2, 3]
剩余空车位 [3]
剩余空车位 []
毛驴无车位
车位都被占用啦 [{'拖拉机': 1}, {'夏利': 2}, {'吉普': 3}]