我有一个带有全局变量的Python文件并定义了一个类:
ROOT = 'https://api.example.com/2.0/'
class Mail(object):
def __init__(self, api_key):
self.name = "FName"
if api_key.find('-'):
dc = api_key.split('-')[1]
global ROOT
print "initing root to: %s" % (ROOT,)
ROOT = ROOT.replace('https://api.', 'https://'+dc+'.api.')
print "initing after replace of ROOT: %s" % (ROOT,)
def pprint(self):
print 'POST to %s' % (ROOT,)
ROOT
全局似乎一旦设置就不会更新:
>>> import pyglob
>>> mc = pyglob.Mail('dfadsfad-us1')
initing root to: https://api.example.com/2.0/
initing after replace of ROOT: https://us1.api.example.com/2.0/
>>> mc.pprint()
POST to https://us1.api.example.com/2.0/
>>> mc3 = pyglob.Mail('dfadsfad-us3')
initing root to: https://us1.api.example.com/2.0/
initing after replace of ROOT: https://us1.api.example.com/2.0/
>>> mc3.pprint()
POST to https://us1.api.example.com/2.0/
>>> mc.pprint()
POST to https://us1.api.example.com/2.0/
有人可以解释一下这是如何工作的以及它为什么会发生?
答案 0 :(得分:1)
完成ROOT = https://us1.api.example.com/2.0/
后,ROOT.replace('https://api.', 'https://'+dc+'.api.')
无法执行任何操作,因为'https://api.'
已不在ROOT
- 您已替换它。
这整个情况看起来非常混乱,你可能想要重构这一点,而不是重新绑定全局变量。