在python中的类中的函数中重用变量

时间:2016-04-15 15:51:54

标签: python

我将尝试用一小段代码解释我面临的问题:

class MyHandler(PatternMatchingEventHandler):
    patterns = ["*.csv","*.processing", "*.transforming","*.loading"]

    def process(self, event):
        eventFileName = event.src_path
        eventType = event.event_type
        if eventType == 'moved':
            eventFileName = event.dest_path
        fileNameWithPath, fileExtension = os.path.splitext(eventFileName)

        if fileExtension == '.processing': 
            # Here some function is called to do something, and then appends ".loading" to the file name
            testVariable = 75.3
        if fileExtension == '.loading':
            print testVariable
    def on_moved(self, event):
        self.process(event)

    def on_created(self, event):
        self.process(event)

if __name__ == '__main__':
    observer = Observer()
    observer.schedule(MyHandler(), path='.')
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()

    observer.join()

当我尝试执行上述操作时,我收到此错误:global name 'testVariable' is not defined哪个有意义,但我如何进行上述操作?我试图在全局定义“testVariable”并启动为0并尝试按照我在上面的代码中显示的方式使用它,但它不能正常工作。 我也尝试在类中启动testVariable为testVariable=0(在“patterns = .....”行之后,但是我收到了这个错误:local variable "testVariable" referenced before assignment指向print testVariable。所以这不起作用同样。

3 个答案:

答案 0 :(得分:2)

"(...)如何完成上述工作?"

在条件语句之外定义def process(self, event): eventFileName = event.src_path testVariable = 0 ... 。例如。这里:

process

这将使其在class MyHandler(PatternMatchingEventHandler): patterns = ["*.csv","*.processing", "*.transforming","*.loading"] testVariable = 0 函数中可用。如果您希望它在整个课程中都可用,您可以在此处定义:

self

但是你必须通过这样的函数中的def process(self, event): ... if fileExtension == '.processing': # Here some function is called to do something, and then appends ".loading" to the file name self.testVariable = 75.3 对象访问它:

facturas_edittext=(EditText)((Activity)context).findViewById(R.id.mye);

答案 1 :(得分:0)

testVariable仅在您具有扩展名" .processing"时才存在。如果它" .loading",程序会尝试打印一个尚未存在的变量。

如果语句没有在Python中创建垃圾收集范围,那么您就不必声明"声明"它在外面,只要你的if-tree中的某个地方,tesVariable就会得到一个值。

答案 2 :(得分:0)

def process(self, event):
    def extension():
        eventFileName = event.src_path
        eventType = event.event_type
        if eventType == 'moved':
            eventFileName = event.dest_path
        return os.path.splitext(eventFileName)[1]

    if extension() == '.processing': 
        ...
    if extension() == '.loading':
        ...