我知道关于这个话题有很多问题(有不好的反馈)。然而下面的代码来自于Fundamentals of Python这本书,这让我觉得作者使用return
而不返回任何东西
一定是有一些原因的
def save(self, fileName = None):
"""Saves pickled accounts to a file. The parameter
allows the user to change filenames."""
if fileName != None:
self.fileName = fileName
elif self.fileName == None:
return # WHAT ARE THE REASONS FOR HAVING THIS LINE? CAN WE DELETE/REMOVE IT?
fileObj = open(self.fileName, "wb")
for account in self.accounts.values():
pickle.dump(account, fileObj)
fileObj.close()
完整代码如下
import pickle
class SavingsAccount(object):
RATE = 0.02 # Single rate for all accounts
def __init__(self, name, pin, balance = 0.0):
self.name = name
self.pin = pin
self.balance = balance
def __str__(self) :
"""Returns the string rep."""
result = 'Name: ' + self.name + '\n'
result += 'PIN: ' + self.pin + '\n'
result += 'Balance: ' + str(self.balance)
return result
def getBalance(self):
"""Returns the current balance."""
return self.balance
def getName(self):
"""Returns the current name."""
return self.name
def getPin(self):
"""Returns the current pin."""
return self.pin
def deposit(self, amount):
"""Deposits the given amount and returns None."""
self.balance += amount
return None
def withdraw(self, amount):
"""Withdraws the given amount.
Returns None if successful, or an
error message if unsuccessful."""
if amount < 0:
return "Amount must be >= 0"
elif self.balance < amount:
return "Insufficient funds"
else:
self.balance -= amount
return None
def computeInterest(self):
"""Computes, deposits, and returns the interest."""
interest = self.balance * SavingsAccount.RATE
self.deposit(interest)
return interest
class Bank(object):
def __init__(self, fileName):
self.accounts = {}
self.fileName = fileName
def __str__(self) :
"""Return the string rep of the entire bank."""
return '\n'.join(map(str, self.accounts.values()))
def makeKey(self, name, pin):
"""Makes and returns a key from name and pin."""
return name + "/" + pin
def add(self, account):
"""Inserts an account with name and pin as a key."""
key = self.makeKey(account.getName(), account.getPin())
self.accounts[key] = account
def remove(self, name, pin):
"""Removes an account with name and pin as a key."""
key = self.makeKey(name, pin)
return self.accounts.pop(key, None)
def get(self, name, pin):
"""Returns an account with name and pin as a key
or None if not found."""
key = self.makeKey(name, pin)
return self.accounts.get(key, None)
def computeInterest(self):
"""Computes interest for each account and
returns the total."""
total = 0.0
for account in self.accounts.values():
total += account.computeInterest()
return total
def save(self, fileName = None):
"""Saves pickled accounts to a file. The parameter
allows the user to change filenames."""
if fileName != None:
self.fileName = fileName
elif self.fileName == None:
return
fileObj = open(self.fileName, "wb")
for account in self.accounts.values():
pickle.dump(account, fileObj)
fileObj.close()
如何修改def save(self, fileName=None)
,使程序会要求用户提供文件名,即:
bank = Bank(None)
bank.add(SavingsAccount("Wilma", "1001", 4000.00))
bank.add(SavingsAccount("Fred", "1002", 1000.00))
bank.save() # a prompt would appear: 'Please provide a name for the file to be saved'
return
后面不跟任何值与写
return None
相同。在您显示的代码中,
return
语句用于在未传递文件名的情况下终止函数,而不是尝试执行
if
和
elif
后面的代码。