Python 命名空间混乱以及如何重用 class 变量

Python namespace confusion and how to re-use class variables

我对以下 python 代码有以下问题:

templates.py
class globalSettings:
    def __init__(self):
        self.tx_wait = 1200
        self.tx_Interval = 30

general.py
from templates import *

class testSuit(object):
    def __init__(self):
        testSuit.settings = globalSettings()
    def readMeasurements(self, filename, revision, lsv):
        testSuit.settings.tx_wait = 100
        testSuit.settings.tx_Interval = 25

test.py
import general

from templates import *

class testcase(object):
    def __init__(self):
        self.settings = general.testSuit.settings

但这给了我:

    self.settings = general_main.testSuit.settings
AttributeError: type object 'testSuit' has no attribute 'settings'

其余代码需要我做的几个导入!

我想要实现的是能够为 globalSettings class 加载不同的设置,但具有默认值。 因此,如果从 excel sheet 中找到,def readMeasurements 实际上是在读取新值。这部分工作正常!

我的代码哪里做错了?

感谢您的宝贵时间!

假设您希望变量是特定于实例的:

class testSuit(object):
    def __init__(self):
        testSuit.settings = globalSettings()
    def readMeasurements(self, filename, revision, lsv):
        testSuit.settings.tx_wait = 100
        testSuit.settings.tx_Interval = 25

应该是:

class testSuit(object):
    def __init__(self):
        self.settings = globalSettings()
    def readMeasurements(self, filename, revision, lsv):
        self.settings.tx_wait = 100
        self.settings.tx_Interval = 25

假设您希望变量是静态的而不是实例定义的,您应该能够使用以下内容:

class testSuit(object):
    settings = globalSettings()
    def readMeasurements(self, filename, revision, lsv):
        settings.tx_wait = 100
        settings.tx_Interval = 25

您可以在 init 函数之外声明 settings = globalSettings()(此处不需要)。

使用您当前的代码,您可以使用以下方法访问变量:

self.settings = general.testSuit.testSuit.settings