api_connection = None
def get_connection():
global api_connection
if api_connection is None:
api_connection = APIConnection(SERVER)
return api_connection
else:
return api_connection
我正在尝试将我的API连接实例存储在全局变量中,以供以后重用。要访问或实例化它,我使用上面的函数。不幸的是,调用函数后api_connection变量没有改变。我究竟做错了什么?
编辑: 这让我更加困惑
>>> c = get_connection()
>>> c == get_connection()
True
>>> c is get_connection()
True
>>> c is api_connection
False
>>> api_connection
>>> api_connection is None
True
答案 0 :(得分:0)
对我有用。我对您的代码进行了如下修改以实现可视化:
>>> api_connection = None
>>>
>>>
>>> def get_connection():
... global api_connection
... if api_connection is None:
... api_connection = 10
... return api_connection
... else:
... return api_connection
...
>>> print(api_connection)
None
>>> get_connection()
10
>>> print(api_connection)
10
我认为此方法APIConnection(SERVER)
也返回None。这就是为什么您看不到变量的变化。您可以检查出这种方法吗?