我用OOP做了一个简单的"账单拆分"情况,出于某种原因,项目的"分区价格"(每当有更多用户加入该项目时就会更新;例如:1个人想要一个5美元的项目=5美元的分区价格,2个人想要它=2.5美元的分区价格,…).
出于某种原因,Participant中的"owes"和Item中的partition\u price不想更新,我也不知道出了什么问题.
class Participant:
#Participant has a name and has items he wants to pitch in for
def __init__(self, name):
self.name = name
self.items = []
self.owes = []
#Append the item (Item class) to the item list
#Append participant's name to the item's participant list
#Append the item's partition price $ to the owes list
def add_Item(self, item):
self.items.append(item)
item.participants.append(self.name)
self.owes.append(item.partition_price)
class Item:
#Item has a name and a price
def __init__(self, name, price):
self.name = name
self.price = price
#List of participants that are pitching in for the item
self.participants = []
#If the list of participants is empty (no participants)
if not self.participants:
#The cost of a "pitch in" for this item is $0
self.partition_price = 0
#Otherwise, the cost of a "pitch in" for this item is its price/number of participants
else:
self.partition_price = price/len(self.participants)
#Create 2 people
matthew = Participant('Matthew')
bob = Participant('Bob')
#Create an item
juice = Item('Apple Juice', 2.99)
#These 2 people wants that item
matthew.add_Item(juice)
bob.add_Item(juice)
#Test
print(f'Matthew wants: {[i.name for i in matthew.items]}')
print(f'Who wants Apple Juice: {juice.participants}')
print(f'Matthew owes: {matthew.owes}')
print(f'The juice costs: {juice.price}, so each person owes: {juice.partition_price} <-- class function')
print(f'The juice ocsts: {juice.price}, so each person owes: {juice.price/len(juice.participants)} <-- external function')
这是它打印的内容:
Matthew wants: ['Apple Juice']
Who wants Apple Juice: ['Matthew', 'Bob']
Matthew owes: [0]
The juice costs: 2.99, so each person owes: 0 <-- class function
The juice ocsts: 2.99, so each person owes: 1.495 <-- external function
马修在第三次打印对账单时应支付1.495英镑.第四个打印语句也应打印1.495.只有外部功能起作用.