简体   繁体   English

当我尝试引用以前在Python中定义的文件变量时,为什么会出现NameError?

[英]Why am I getting a NameError when I try to reference to a file variable I have previously defined in Python?

I am trying to write to a .txt file, but I get the error 我正在尝试写入.txt文件,但出现错误

File "C:\Python34\Timer.py", line 262, in Lap
outfile.write(timenow + str(tempo)+ "\n")
NameError: name 'outfile' is not defined

I have already defined 'outfile' in: 我已经在以下位置定义了“输出文件”:

class StopWatch(Frame):  
    """ Implements a stop watch frame widget. """                                                                
    def __init__(self, parent=None, **kw):        
        Frame.__init__(self, parent, kw, bg="black")
        self._start = 0.0        
        self._elapsedtime = 0.0
        self._running = 0
        self.timestr = StringVar()
        self.lapstr = StringVar()
        self.e = 0
        self.m = 0
        self.makeWidgets()
        self.laps = []
        self.lapmod2 = 0
        self.today = time.strftime("%d %b %Y %H-%M-%S", time.localtime())
        timenow = time.strftime("%d %b %Y %H:%M:%S", time.localtime())
        outfile = open("lap_timings_and_time.txt","wt") 
        outfile.write(timenow+ "\n")

And tried to write to the file 'lap_timings_and_time.txt' in the following code: 并尝试通过以下代码写入文件“ lap_timings_and_time.txt”:

def Lap(self):
    '''Makes a lap, only if started'''
    tempo = self._elapsedtime - self.lapmod2
    timenow = time.strftime("%d %b %Y %H:%M:%S", time.localtime())
    if self._running:
        self.laps.append(self._setLapTime(tempo))
        self.m.insert(END, self.laps[-1])
        self.m.yview_moveto(1)
        self.lapmod2 = self._elapsedtime
        outfile.write(timenow + str(tempo)+ "\n")

I'm a beginner at Python and can't figure out why the error is occurring. 我是Python的初学者,无法弄清楚为什么会发生错误。 Any help is greatly appreciated! 任何帮助是极大的赞赏!

outfile.write(timenow + str(tempo)+ "\n")

This should be: 应该是:

self.outfile.write(timenow + str(tempo)+ "\n")

You'll also want to change the last two lines of your constructor ( __init__ ) to: 您还需要将构造函数的最后两行( __init__ )更改为:

    self.outfile = open("lap_timings_and_time.txt","wt") 
    self.outfile.write(timenow+ "\n")

Update: A bit of explanation as per the comments... 更新:根据评论有一些解释...

What you were encountering was a "Scoping Issue". 您遇到的是一个“范围问题”。 (See: Scoping and Namespaces ). (请参阅: 作用域和命名空间 )。

In general referencing attributes of an object requires "explicit" referenecing. 通常,引用对象的属性需要“显式”引用。

ie: 即:

class Foo(object):

    def __init__(self):
        self.my_attr = "foo"

    def foo(self):
        return self.my_attr

You cannot reference my_attr by the expression return my_attr as my_attr is neither in Foo.foo() scope nor part of the module's scope or even declared a global. 您不能通过表达式return my_attr引用my_attr ,因为my_attr既不在Foo.foo()范围内,也不在模块范围内,甚至没有声明为全局Foo.foo()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM