写一个共享单车的代码
时间: 2023-12-01 18:08:32 浏览: 68
共享单车代码.docx
这里是一个简单的共享单车的 Python 代码,实现了用户注册、借车、还车、充值等功能:
```python
class User:
def __init__(self, name, balance=0):
self.name = name
self.balance = balance
self.borrowed_bike = None
def borrow_bike(self, bike):
if self.borrowed_bike is not None:
print("You have already borrowed a bike!")
return False
if bike.borrow_by is not None:
print("Sorry, this bike has been borrowed by someone else!")
return False
self.borrowed_bike = bike
bike.borrow_by = self
print("You have successfully borrowed a bike!")
return True
def return_bike(self):
if self.borrowed_bike is None:
print("You haven't borrowed any bike yet!")
return False
self.borrowed_bike.borrow_by = None
self.borrowed_bike = None
print("You have successfully returned the bike!")
return True
def recharge(self, amount):
self.balance += amount
print("You have successfully recharged {} yuan!".format(amount))
class Bike:
def __init__(self, bike_id):
self.bike_id = bike_id
self.borrow_by = None
class BikeSharingSystem:
def __init__(self):
self.users = {}
self.bikes = {}
self.bike_id_counter = 0
def add_user(self, name, balance=0):
if name in self.users:
print("User {} already exists!".format(name))
return False
self.users[name] = User(name, balance)
print("User {} has been added to the system!".format(name))
return True
def add_bike(self):
bike_id = str(self.bike_id_counter)
self.bike_id_counter += 1
self.bikes[bike_id] = Bike(bike_id)
print("Bike {} has been added to the system!".format(bike_id))
return True
def borrow_bike(self, user_name, bike_id):
if user_name not in self.users:
print("User {} does not exist!".format(user_name))
return False
if bike_id not in self.bikes:
print("Bike {} does not exist!".format(bike_id))
return False
return self.users[user_name].borrow_bike(self.bikes[bike_id])
def return_bike(self, user_name):
if user_name not in self.users:
print("User {} does not exist!".format(user_name))
return False
return self.users[user_name].return_bike()
def recharge(self, user_name, amount):
if user_name not in self.users:
print("User {} does not exist!".format(user_name))
return False
self.users[user_name].recharge(amount)
return True
```
使用方法:
```python
system = BikeSharingSystem()
system.add_user("Alice", 100)
system.add_user("Bob", 50)
system.add_bike()
system.borrow_bike("Alice", "0")
system.borrow_bike("Bob", "0")
system.return_bike("Alice")
system.borrow_bike("Bob", "0")
system.recharge("Alice", 50)
```
阅读全文