我们正在使用python2创建一个小型的基于文本的银行应用程序,我们必须使用用户的钱来执行许多功能。例如:我创建了一个变量a = 100
,并将该变量与global a
一起在函数中使用。但是我的老师不允许我们使用术语global
,因此我必须使用global
以外的其他术语。
例如:
a = 100
def withdraw():
global a
ko = input("Please enter the amount you want to withdraw:")
if ko > a:
print "You don't have " + " " + str(ko) + " " + "in your account."
print "Going back to main menu..."
else:
a = a - ko
print str(ko) + "Dollar" + "withdrawn from your account"
答案 0 :(得分:1)
您可以将全局变量(在此示例中,我们将使用account
代替a
)作为您的局部变量 main并在需要它的每个函数中使用它。在这种情况下,如下所示:
def withdraw(account):
# ... code here
account -= ko
print str(ko) + " Dollar withdrawn from your account"
return account
您会这样称呼它
account = withdraw(account)
答案 1 :(得分:1)
在此特定示例中,我只需传入a
,然后将其返回给调用者即可:
# Renamed a to balance
def withdraw(balance):
# Take input as before
return balance - ko
a = 100
a = withdraw(a)
请尽可能传递任何相关数据,然后将所有结果返回。
答案 2 :(得分:0)
有很多方法可以避免在代码中使用全局变量,例如通过使用实例变量。
正如您的老师所建议的那样,您应该避免使用全局变量,因为您可能会错误地声明另一个具有相同名称的变量,然后在阅读代码时,不清楚哪个变量正在被访问,从而难以调试代码。
我建议类似以下内容:
class BankAccount():
def __init__(self, initial_balance):
self.balance = initial_balance
def withdraw(self, withdraw_amount=0):
if withdraw_amount > self.balance:
print "You don't have " + " " + str(withdraw_amount) + " " + "in your account."
print "Going back to main menu..."
else:
self.balance -= withdraw_amount
print str(withdraw_amount) + "Dollar" + "withdrawn from your account"
在此之后,您可以创建银行帐户的实例,并通过以下方式从中取款:
bank_account = BankAccount(initial_balance=1000)
bank_account.withdraw(withdraw_amount=100)