[英]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类加载不同的设置,但是具有默认值。 因此,如果从excel表格中找到,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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.