如何避免在Python2.7中使用global?
我们正在使用python2创建一个小型的基于文本的银行应用程序,我们必须使用用户的钱来实现许多功能。例如:我创建了一个变量如何避免在Python2.7中使用global?,python,python-2.7,Python,Python 2.7,我们正在使用python2创建一个小型的基于文本的银行应用程序,我们必须使用用户的钱来实现许多功能。例如:我创建了一个变量a=100,并将该变量与global a一起使用在函数中。但是我的老师不允许我们使用术语global,所以我不得不使用global以外的其他术语。 例如: a = 100 def withdraw(): global a ko = input("Please enter the amount you want to with
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"
您可以将全局变量(在本例中,我们将使用
account
而不是a
)设置为main中的局部变量,并在需要它的每个函数中使用它。在这种情况下,类似这样的情况:
def withdraw(account):
# ... code here
account -= ko
print str(ko) + " Dollar withdrawn from your account"
return account
你会这样称呼它吗
account = withdraw(account)
在这个特定的示例中,我只需传入
a
,然后将其返回给调用者:
# Renamed a to balance
def withdraw(balance):
# Take input as before
return balance - ko
a = 100
a = withdraw(a)
只要有可能,传入任何相关数据,并返回任何结果 有许多方法可以避免在代码中使用全局变量,例如使用实例变量 正如您的老师所建议的,您应该避免使用全局变量,因为您可能会错误地声明另一个具有相同名称的变量,然后在读取代码时,将看不出访问了哪个变量,这使得调试代码变得很困难 我建议类似的做法:
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)
你甚至不需要在这里上课。您可以将
a
传递到函数中,然后返回a
的新值。我敢打赌你的老师有他们喜欢的特定方法,我们不知道是哪种方法:最好的选择是寻求澄清。我知道这个词,但教授也不允许使用。我尝试使用这个解法,但我看到了错误;TypeError:Draw(balance)只接受1个参数(给定0)@EnesUzun注意我如何使用代码底部的Draw
。我正在传递一个a
。你错过了那部分。平衡系统正在工作,但我有几个问题。当我编写returnbalance-ko时,我无法在“return”行下编写任何代码,我必须返回主菜单。最后一个问题是,当我使用取款功能并返回主菜单,调用存款功能和打印余额时,结果将是“100”,正如我们在开始时所写的那样。“平衡”值没有改变。@对于第一个问题,函数在运行return
时结束。该函数在返回时退出。对于第二个问题,请再次注意我是如何编写代码的。您需要重新分配a
。我以特定的方式编写代码是有原因的。根据您的问题,您需要回顾return
的工作原理。这是一个非常重要的话题,所以一定要更彻底地复习。