简体   繁体   English

Python 未定义全局变量 - 在内部声明 Class

[英]Python Global Variable Not Defined - Declared inside Class

I've seen a lot of questions on global variables, but for some reason I still can't get mine to work.我已经看到很多关于全局变量的问题,但出于某种原因我仍然无法让我的工作。

Here is my scenario - I have my individual test cases and a separate python script that includes different functions for the various error messages you can get in the application I'm testing.这是我的场景——我有自己的测试用例和一个单独的 python 脚本,其中包含针对您在我正在测试的应用程序中可能收到的各种错误消息的不同函数。 If one of the validations fails, I want the function to increment a failure variable and then the main test script will check to see if it's a pass or fail.如果其中一项验证失败,我希望 function 增加一个失败变量,然后主测试脚本将检查它是通过还是失败。

class ErrorValidations:
    failures = 0
    def CheckforError1(driver):
        global failures
        try:
            if error1.is_displayed():
                failures += 1

    def CheckforError2(driver):
        global failures
        try:
            if error2.is_displayed():
                failures += 1

    def CheckforError3(driver):
        global failures
        try:
            if error3.is_displayed():
                failures += 1

This is a heavily edited example of where the validations get used:这是一个经过大量编辑的示例,说明了在何处使用验证:

from functionslist import ErrorValidations


def test(driver, browser, test_state):

    _modules = driver.find_elements_by_xpath('//div[@class="navlink"]')

    for i in _modules:
        i.click()

        ErrorValidations.CheckforError1(driver)
        ErrorValidations.CheckforError2(driver)
        ErrorValidations.CheckforError3(driver)

        if ErrorValidations.failures > 0:
            driver.report.AppendToReport( i.text, "The " + i.text + "page was not able to load without errors.", "fail", "")
        else:
            driver.report.AppendToReport( i.text,  "The " + i.text + "page was able to load without errors.", "pass", "")

The test is not properly incrementing the failures variable and I get the error: name 'failures' is not defined, but I'm not sure where else to define it.测试没有正确地增加 failures 变量,我收到错误:未定义名称“failures”,但我不确定在哪里定义它。

You're declaring a class attribute 'failures', not a global, within the ErrorValidations您在 ErrorValidations 中声明了 class 属性“失败”,而不是全局属性

Instead of using global failures try:不要使用全局失败,而是尝试:

class ErrorValidations:
    failures = 0

    def CheckforError1(driver):
        try:
            if error1.is_displayed():
                ErrorValidations.failures += 1

A true global would be declared outside of the class真正的全局将在 class 之外声明

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

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