我有一个带有全局var的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/
有人能解释一下这种情况是如何发生的以及为什么会发生吗?
制作完ROOT = https://us1.api.example.com/2.0/
后,ROOT.replace('https://api.', 'https://'+dc+'.api.')
什么都不做,因为'https://api.'
已不在ROOT
中--您已经替换了它。
整个情况看起来非常混乱,您可能想要重构它,而不是重新绑定全局。