写这样一个简单的类用到 n 多 self ,个人觉得有点冗余,大家什么感觉?我也是初学,或者有好的方法可以避免?
class VendingMachine:
"""A vending machine that vends some product for some price."""
def __init__(self,stockName,stockPrice):
self.stockName = stockName
self.stockPrice = stockPrice
self.stockNumber = 0
self.balance = 0
def vend(self):
if self.stockNumber == 0:
return "Machine is out of stock."
elif self.balance < self.stockPrice:
return 'You must deposit $' + str(self.stockPrice - self.balance) + ' more.'
else:
self.stockNumber -= 1
change = self.balance - self.stockPrice;
self.balance = 0
if change == 0:
return 'Here is your candy.'
else:
return 'Here is your candy and $'+ str(change) +' change.'
def deposit(self,amount):
self.balance += amount
if(self.stockNumber == 0):
return 'Machine is out of stock. Here is your $' + str(self.balance) + '.'
return "Current balance: $" + str(self.balance)
def restock(self,stockNumber):
self.stockNumber += stockNumber
return "Current candy stock: " + str(self.stockNumber)
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.