【问题标题】:Why does namespace after method call changes?为什么方法调用后命名空间会发生变化?
【发布时间】:2009-09-01 09:07:54
【问题描述】:

我正在创建一个类,但在 python 中的命名空间有些问题。

您可以看到下面的代码,它大部分工作正常,但在调用guiFrame._stateMachine() 之后,时间模块不知何故不再定义。

如果我在_stateMachine() 中重新导入时间模块,它可以工作。但是为什么我在头部导入时间模块时不在命名空间中呢?

我错过了什么吗?

错误信息:

  File "C:\Scripts\Python\GUI.py", line 106, in <module>
    guiFrame._stateMachine()
  File "C:\Scripts\Python\GUI.py", line 74, in _stateMachine
    self.tempfile.write('%s cpuUMTS %s\n' % (time.asctime(time.localt
f.load.cpuThreadsValue['10094']))
UnboundLocalError: local variable 'time' referenced before assignment

代码:

import os
import cpu_load_internal
import throughput_internal
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

from Tkinter import *
import tkMessageBox
import time
class GUIFramework(Frame):
    """This is the GUI"""

    def __init__(self,master=None):
        """Initialize yourself"""

        """Initialise the base class"""
        Frame.__init__(self,master)

        """Set the Window Title"""
        self.master.title("Type Some Text")

        """Display the main window
        with a little bit of padding"""
        self.grid(padx=10,pady=10)
        self.CreateWidgets()
        plt.figure(1)

    def _setup_parsing(self):
        self.load = cpu_load_internal.CPULoad('C:\Templogs')
        self.throughput = throughput_internal.MACThroughput('C:\Templogs')
        self.tempfile = open('output.txt','w')
        self.state = 0        

    def _parsing(self):
        self.load.read_lines()
        self.throughput.read_lines()
        self.cpuLoad.set(self.load.cpuThreadsValue['10094'])
        self.macThroughput.set(self.throughput.macULThroughput)         

    def __change_state1(self):
        self.state = 2

    def __change_state3(self):
        self.state = 3     

    def CreateWidgets(self):
        """Create all the widgets that we need"""

        """Create the Text"""
        self.cpuLoad = StringVar()
        self.lbText1 = Label(self, textvariable=self.cpuLoad)
        self.lbText1.grid(row=0, column=0)

        self.macThroughput = StringVar()
        self.lbText2 = Label(self, textvariable=self.macThroughput)
        self.lbText2.grid(row=0, column=1)

        self.butStart = Button(self, text = 'Start', command = self.__change_state1)
        self.butStart.grid(row=1, column=0)

        self.butStop = Button(self, text = 'Stop', command = self.__change_state3)
        self.butStop.grid(row=1, column=1)

    def _stateMachine(self):
        if (self.state == 2):
            print self.throughput.macULUpdate
            print self.load.cpuUpdate

            if self.load.cpuUpdate:
                self.load.cpuUpdate = 0
                print 'cpuUMTS %s\n' % (self.load.cpuThreadsValue['10094'])
                self.tempfile.write('%s cpuUMTS %s\n' % (time.asctime(time.localtime()), self.load.cpuThreadsValue['10094']))            

            if self.throughput.macULUpdate:
                self.throughput.macULUpdate = 0
                print 'macUL %s %s\n' % (self.throughput.macULThroughput, self.throughput.macULThroughputUnit)
                self.tempfile.write('%s macUL %s %s\n' % (time.asctime(time.localtime()), self.throughput.macULThroughput, self.throughput.macULThroughputUnit))

        if (self.state == 3):
            self.tempfile.seek(0)
            plt.plot([1,2,3],[1,4,6])
            plt.savefig('test.png')
            self.state == 0
            while 1:
                try:
                    line = (self.tempfile.next())
                except:
                    break

                if 'cpuUMTS' in line:
                    line.split
                    time = 4


if __name__ == "__main__":
    guiFrame = GUIFramework()
    print dir(guiFrame)
    guiFrame._setup_parsing()
    guiFrame.state = 2
    while(1):
        guiFrame._parsing()
        guiFrame._stateMachine()
        guiFrame.update()
        time.sleep(0.1)

【问题讨论】:

    标签: python namespaces


    【解决方案1】:

    你为什么分配给time?您不能将其用作局部变量,它会使模块黯然失色!如果您仔细观察,它会抱怨您在分配给它之前使用了time——因为将它用作_stateMachine 中的局部变量。

    time = 4
    

    【讨论】:

    • 哎呀..(:我有点得意忘形,不知何故对错误感到困惑。当然这是问题所在。谢谢!
    【解决方案2】:

    您似乎将时间用作变量。这里发生了什么:

    “C:\Scripts\Python\GUI.py”,第 74 行

    【讨论】:

      【解决方案3】:

      你尝试在这个方法中赋值给变量time

      time = 4
      

      因此编译器假定时间必须是一个局部变量,这是不正确的。这就是为什么当您想使用模块time 时出现此错误的原因,即使您在分配给time 之前尝试使用该模块。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-03
        • 2019-12-20
        • 2021-07-15
        • 1970-01-01
        • 2022-01-06
        相关资源
        最近更新 更多