【问题标题】:How to access globlal variable within a class method using python 3.x如何使用 python 3.x 在类方法中访问全局变量
【发布时间】:2019-10-31 13:16:12
【问题描述】:

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

我试过设置 self.filename = 文件名。我尝试在类之外设置全局文件名 = None,然后在类 init 本身内设置文件名。我在下面包含了 sn-p 代码:

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")
'SNMPPage' object has no attribute 'filename'

我希望使用 create_batchfile 创建文件(这是成功的),但是当我运行 start_batchfile 方法时,它失败了,因为 SNMPPage 没有属性“文件名”


【问题讨论】:

  • 这个文件名是否必须在所有类实例之间或相同对象方法之间共享?
  • @LiorCohen 实际上只是在两个对象方法之间。一个创建一个批处理文件,另一个运行它。

标签: python-3.x class oop variables global


【解决方案1】:

根据您在评论中的说明。

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

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)

【讨论】:

  • 我很感激。这次它奏效了。不知道有什么区别,因为我之前尝试过您的解决方案,但仍然失败,但现在可以了。日志记录方面仍然有点偏离,但我会自己调试。我还在上课。我认为一旦在方法内的局部范围内创建了一个变量,它在使用后就会“销毁”,并且不能被其他方法使用。
  • 关于局部变量你是对的,但 self.filenmae 不是局部变量,它是一个对象属性(在其他语言中调用成员)
猜你喜欢
  • 2014-07-29
  • 2015-01-17
  • 1970-01-01
  • 2012-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多