[英]How to change a global variable in python?
I am accessing data from different accounts from an online platform over their API. 我正在通过API通过在线平台从不同帐户访问数据。 I have created a class called Account that holds all the information necessary to access this API. 我创建了一个名为Account的类,其中包含访问此API所需的所有信息。 I want to be able to set the account (and the necessary info to gain access) each time before I make an API request. 我希望能够在每次发出API请求之前设置帐户(以及获得访问权限所需的信息)。 I tried to make a function that will set a global variable Acct to the proper account class instance but after I call choose_account(), Acct continues to return '', is there a better way to handle this type of procedure? 我试图制作一个将全局变量Acct设置为正确的帐户类实例的函数,但是在我调用choose_account()之后,Acct继续返回'',是否有更好的方法来处理此类过程?
Acct = ''
def choose_account():
global Acct
get = raw_input(r'Adap1, Adap2, Adap3, or Adap4? ')
if get == 'Adap1':
Acct = Adap1
elif get == 'Adap2':
Acct = Adap2
elif get == 'Adap3':
Acct = Adap3
elif get == 'Adap4':
Acct = Adap4
else:
print ("Please type Adap1, Adap2, Adap3, or Adap4 ")
Edit: show Account and Adap1 etc 编辑:显示帐户和Adap1等
class Account():
def __init__(self, name, username, password, org_id):
self.name = name
self.username = username
self.password = password
self.org_id = org_id
def update_pw(self, pw):
self.password = pw
Adap1 = Account('Adap1', 'username', 'password', 'org_id')
Sorry, but use of global variables in that way is not usually a good way to go. 抱歉,以这种方式使用全局变量通常不是一个好方法。 You are probably new to programming, so I don't want you to feel you are being "told off", but it would be much more sensible to have the function return a value, and then set the global variable with a statement like 你可能是新的节目,所以我不希望你觉得你被“关说”,但它会更合理有函数返回一个值,然后设置全局变量中包含的声明
Acct = choose_account()
In which case your function ought to look more like this (untested code): 在这种情况下,您的函数应该看起来像这样(未经测试的代码):
def choose_acct():
while True:
get = raw_input(r'Adap1, Adap2, Adap3, or Adap4? ')
if get == "Adap1":
return Adap1
elif get == "Adap2":
return Adap2
elif get == "Adap3":
return Adap3
elif get == "Adap4":
return Adap4
Better still, you could consider a data-driven approach to the problem, and define a dictionary like 更好的是,您可以考虑采用数据驱动的方法来解决问题,并定义一个字典,例如
adict = {"Adap1": Adap1, "Adap2": Adap2, "Adap3": Adap3, "Adap4": Adap4}
Then your function could read (again, untested) 然后您的函数可以读取(再次,未经测试)
def choose_acct():
while True:
get = raw_input(r'Adap1, Adap2, Adap3, or Adap4? ')
result = adict.get(get, None)
if result:
return result
As your experience level grows you will start to recognise the difference between good and bad code, but you made a pretty good attempt. 随着您的经验水平的提高,您将开始认识到好代码和坏代码之间的区别,但是您做了相当不错的尝试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.