简体   繁体   English

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

[英]re-using the variable in a function in a class in python

I will try to explain the problem I am facing with a small piece of code: 我将尝试用一小段代码来解释我面临的问题:

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()

When I try to do the above I am getting this error: global name 'testVariable' is not defined which kinda makes sense but how do I make the above work? 当我尝试执行上述操作时,出现此错误: global name 'testVariable' is not defined哪种含义有意义,但是如何进行以上工作? I tried to define "testVariable" globally and initiated to 0 and tried using it the way I showed in above code but it did not work as well. 我尝试全局定义“ testVariable”并初始化为0,并尝试使用上面代码中显示的方式使用它,但效果不佳。 I also tried initiating testVariable as testVariable=0 inside the class (right after "patterns = ....." line but I got this error: local variable "testVariable" referenced before assignment pointing towards print testVariable . So that didnot work as well. 我也尝试在类内部将testVariable初始化为testVariable=0testVariable=0在“ patterns = .....”行之后,但是我遇到了这个错误: local variable "testVariable" referenced before assignment指向print testVariable local variable "testVariable" referenced before assignment 。 。

"(...) how do I make the above work?" “(...)我如何进行上述工作?”

By defining testVariable outside your conditional statements. 通过在条件语句之外定义testVariable Eg here: 例如:

def process(self, event):
    eventFileName = event.src_path
    testVariable = 0
    ...

This will make it available within the process function. 这将使其在process功能中可用。 If you want it to be available throughout the class, you can define it here: 如果希望在整个课程中都可以使用它,可以在这里定义它:

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

But then you have to access it via the self object within functions like so: 但是然后您必须通过以下函数中的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

testVariable only exists if you have the extension ".processing". 仅当扩展名为“ .processing”时,testVariable才存在。 If it's ".loading", the program tries to print a variable that hasn't been made to exist. 如果它是“ .loading”,程序将尝试打印一个尚未存在的变量。

If statements do not create a garbage collecting scope in Python, so you don't have to "declare" it outside, so long as somewhere in your if-tree, tesVariable gets a value. 如果语句未在Python中创建垃圾回收范围,那么您不必在外部“声明”它,只要在if-tree中的某个位置,tesVariable即可获取值。

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':
        ...

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

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