【发布时间】:2018-02-02 18:55:47
【问题描述】:
导入模块,connection_status_message.py:
connection_status_message = "Not Connected"
尝试除了文件,connect_to_server.py:
from Server.connection_status_message import connection_status_message
def connect_to_server(host,user,password):
try:
connect(host,user,password)
except NoConnection:
connection_status_message = "Could not reach host..."
return
...
问题是变量正试图本地化。所以我阅读了这个问题并了解了如何引用全局变量:
def connect_to_server(host,user,password):
try:
connect(host,user,password)
except NoConnection:
global connection_status_message
connection_status_message = "Could not reach host..."
return
...
但是现在 PyCharm 声明顶部的 import 语句不再被使用。
如何让这个 Try/Except 使用导入的变量?
【问题讨论】:
-
考虑使用 OOP 方法,创建一个名为
Connection的类来处理connect()并具有connection_status_message的属性。 -
pass是一个关键字。您不能将其用作变量名。 -
pass只是一个缩写。我不知道这是一个关键字,所以我在问题中将其更改为password以避免混淆。对不起。
标签: python global try-except