Python 3.x 如何使用Python3.x在类方法中访问globlal变量

Python 3.x 如何使用Python3.x在类方法中访问globlal变量,python-3.x,class,oop,variables,global,Python 3.x,Class,Oop,Variables,Global,我遇到了一个问题,我有一个类方法,它创建了一个批处理文件,并将文件名存储在一个名为“filename”的变量中。我有另一个方法运行批处理文件,调用在另一个方法中创建的“filename”。但是我得到的响应类对象没有属性“filename”。如何在一个方法中创建此变量,并在同一类中的另一个方法中调用它 我已尝试设置self.filename=filename。我尝试在类之外设置全局文件名=None,然后在类init本身内设置文件名。我已将代码片段包括在下面: class SNMPPage(tk.F

我遇到了一个问题,我有一个类方法,它创建了一个批处理文件,并将文件名存储在一个名为“filename”的变量中。我有另一个方法运行批处理文件,调用在另一个方法中创建的“filename”。但是我得到的响应类对象没有属性“filename”。如何在一个方法中创建此变量,并在同一类中的另一个方法中调用它

我已尝试设置self.filename=filename。我尝试在类之外设置全局文件名=None,然后在类init本身内设置文件名。我已将代码片段包括在下面:

class SNMPPage(tk.Frame):
    def __init__(self, root=None):
        tk.Frame.__init__(self, root)
        self.root = root
        self.root.title('SNMP Get Set Test')
        global filename
        self.init_gui()

    def create_batch(self):
        i = 0
        #path = os.getcwd()
        global filename
        #ping_set = 'ping -n 1 ' + e1.get() + ' | find "TTL=" >null\nif errorlevel 1 (\n    echo host not reachable\n    pause\n)\n'
        snmp_get = 'snmpget' + " -Os" + " -mall " + "-c " + self.e3.get() + ' -v2c' + ' ' + self.e1.get() + ' ' + self.e2.get() + "\n"
        snmp_set = 'snmpset' + " -Os" + " -mall " + "-c " + self.e3.get() + ' -v2c' + ' ' + self.e1.get() + ' ' + self.e2.get() + \
                    ' i' + ' 1\n'
        timeout = 'timeout ' + self.e4.get() + '\n'
        filename = path + '\\SNMPBatchrun' + getdatetime('datetime') + ".bat"
        with open(filename, 'w+') as outfile:
            while i < 10:
                #outfile.write(ping_set)
                outfile.write(snmp_get)
                outfile.write(snmp_set)
                outfile.write(timeout)
                i += 1
        loggermodule.module_logger.debug('Batch File Created: {}'.format(filename))
        logger.debug('Batch file created: {}'.format(filename))


    def start_batch(self):
        try:
            global filename
            logger.debug('Starting batch file execution')
            loggermodule.module_logger.debug('Starting batch file execution')
            #s = subprocess.check_output([filename]).decode('utf-8')
            process = subprocess.Popen([filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            output, code = process.communicate()
            self.root.update()

            ''' Logger'''
            for line in code.decode('utf-8').splitlines():
                if 'Waiting for' not in line:
                    logger.debug(line)
                    loggermodule.module_logger.debug(line)
                for line in output.decode('utf-8').splitlines():
                    if 'Waiting for' not in line:
                        logger.debug(line)
                        loggermodule.module_logger.debug(line)
            loggermodule.module_logger.debug("Batch job completed")
            logger.debug("Batch job completed")
            # with open(log_file, 'w+') as outfile:
            #    for line in s.splitlines():
            #        outfile.write(line)
            return self.output
        except subprocess.CalledProcessError as e:
            logger.exception(e)
            loggermodule.module_logger.debug(e)
            loggermodule.module_logger.debug("There was an error, Batch file stopped. Check Log file")
我希望使用create\u batchfile创建该文件(成功),但当我运行start\u batchfile方法时,由于SNMPPage没有属性“filename”而失败


根据您在评论中的澄清

为了在方法之间共享变量,这应该是一个对象属性。 我不知道为什么它对你不起作用,但你应该使用这个基本模式

class SNMPPage(tk.Frame):
  def __init__(self, root=None):
    self.filename = None # this is not a must but a very good practice
    ....

  def create_batch(self):
    self.filename = 'foo'

  def start_batch(self):
    # use self.filename
    print(self.filename)

这个文件名必须在所有类实例之间共享还是在相同的对象方法之间共享?@LiorCohen实际上只是在两个对象方法之间共享。一个创建一个批处理文件,另一个运行它。我很感激。这次成功了。不确定区别是什么,因为我之前尝试过你的解决方案,但仍然失败,但现在一切正常。日志方面仍然有点不对劲,但我将自己调试它。我还在上课。我认为,一旦在方法的局部范围内创建了变量,它在使用后会被“销毁”,并且不能由其他方法使用。关于局部变量,您是对的,但self.filenmae不是局部变量,它是一个对象属性(在其他语言中称为member)

class SNMPPage(tk.Frame):
  def __init__(self, root=None):
    self.filename = None # this is not a must but a very good practice
    ....

  def create_batch(self):
    self.filename = 'foo'

  def start_batch(self):
    # use self.filename
    print(self.filename)