如何在Python中将变量信息从一个类传递到另一个类

时间:2014-01-23 20:12:27

标签: python class unit-testing global-variables parameter-passing

我真的很挣扎如何在Python中将变量信息从一个类传递到另一个类。我有一个我正在创建的程序,它根据扩展名或文件名检测文件类型。我最初将文件名设置为args是什么(现在硬编码,但将使用argparse)。如果我检测到一个zip文件,那么我将解压缩zip并拉出test.xml并将该文件路径重新分配给变量。但是,当我从另一个类调用它时,我得到了旧路径(从args分配)。我是Python新手,这是我的屁股。希望有人可以帮助我。以下是我的代码示例:

主要课程:

class ValidateTest(Parameterize.ParametrizedTestCase):
    def __init__(self):
        parser = argparse.ArgumentParser(description='' + '')
        parser.add_argument('-d', '--driver', help='Path and file name of xml or zip driver file', required=True)
        parser.add_argument('-v', '--verbosity',
                            help='Verbosity for test output.  1 for terse, 2 for verbose.  Default is verbose',
                            default=1, type=int)
        args = "c:\\test.zip"
        self.filename = args
        #self.verbosity = args.verbosity

    def main(self):
        # Test for a valid xml file.  This could be a .xml, .zip, or test.xml
        if os.path.splitext(os.path.basename(self.filename))[1] == '.xml':
            self.assertTrue(True, logger.passed("A file with a valid extension of '.xml' was detected."))
        elif os.path.basename(self.filename) == 'test.xml':
            self.assertTrue(True, logger.passed("A file with the valid name of 'test.xml' was detected."))
        elif os.path.splitext(os.path.basename(self.filename))[1] == '.zip':
            self.assertTrue(True, logger.passed("A file with the valid extension of '.zip' was detected."))

            # Test if the .zip is a valid zip file
            if zipfile.is_zipfile(self.filename):
                self.assertTrue(True, logger.passed("%s is a valid zip file" % self.filename))
                self.assertTrue(True, logger.info("Extracting .zip to obtain test.xml."))

                # Extract the .zip and pull out the test.xml.
                tempDirectory = tempfile.mkdtemp(suffix="", prefix="TEST_")
                with zipfile.ZipFile(self.filename) as zf:
                    zf.extractall(tempDirectory)
                    self.filename = tempDirectory + os.path.sep + "test.xml"
            else:
                self.assertTrue(False, logger.failed("%s is not a valid zip file" % self.filename))
        else:
            self.assertTrue(False, logger.failed("Invalid file detected.  A valid file has a .xml or .zip extension.  Extension must be lower-case.  test.xml is also a valid file"))
        # TODO: Remove the temp directory after complete.
        return validate.run(self.filename) == False

if __name__ == "__main__":
    validateTest = ValidateTest()
    sys.exit(validateTest.main())

正如您在 init 函数中看到的,我为self.filename指定了args变量的值。稍后在main函数中我检测到一个zip文件,然后设置self.filename =新的文件路径和名称。但是,正如您将在下面看到的,我从另一个类调用此self.filename变量,并获得从args分配的原始值。见下文:

class Tests(Parameterize.ParametrizedTestCase):
    def test_validateIrCode(self, ircode):
        driver = ElementTree.parse(Main.ValidateTest().filename)

filename的值是c:\ test.zip而不是提取的文件...比如,c:\ temp \ test.xml

如果你们中的任何人能够提供一些明确的例子,我会很高兴。我已经尝试使用全局变量并将变量作为参数传递但我显然做错了,因为我得到语法错误或相同的结果。

0 个答案:

没有答案