gpt4 book ai didi

Python 全局未在新对象实例中更新

转载 作者:太空宇宙 更新时间:2023-11-03 18:12:10 25 4
gpt4 key购买 nike

我有一个带有全局变量的 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 中--你已经替换了它。

整个情况看起来非常困惑,您可能想要重构它以根本不重新绑定(bind)全局变量。

关于Python 全局未在新对象实例中更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25715566/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com