【问题标题】:Python try except not using imported variablePython尝试除了不使用导入的变量
【发布时间】: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


【解决方案1】:

我无法复制您的问题,但如果您的 import 行存储在函数下,则变量为 nonlocal instead of global

def connect_to_server(host,user,password):
    try:
        connect(host,user,password)
    except NoConnection:
        nonlocal connection_status_message
        connection_status_message = "Could not reach host..."

另一种方法是不将变量直接加载到您的命名空间中,这样您就可以参考它的来源以避免创建局部变量:

from Server import connection_status_message as csm
csm.connection_status_message

# "No Connection"

def func():    
    csm.connection_status_message = "Could not reach host..."

csm.connection_status_message

# "Could not reach host..."

你也可以考虑创建一个类来处理所有这些作为一个对象:

class Connection(object):
    def __init__(self):
        self.connection_status_message = "No Connection"
        # TODO: initialize your class

    def connect(self, host, user, password):
        # TODO code connect criteria stuff here

    def connect_to_server(self, host, user, password):
        try:
            self.connect(host,user,password)
        except NoConnection:
            self.connection_status_message = "Could not reach host..."
            # ... return whatever ...#

现在您可以执行from Server import Connection 并创建一个本地Connection 对象来操作:

conn = Connection()
conn.connect_to_server(host, user, password)

这可能很明显,但无论如何,该值仅在执行期间存储在内存中。实际的 connection_status_message.py 永远不会使用此值更新。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-25
    • 2019-01-29
    • 1970-01-01
    • 2021-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多