gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 20:39:22 26 4
gpt4 key购买 nike

我已经看到很多关于全局变量的问题,但出于某种原因我仍然无法让我的工作。

这是我的场景 - 我有自己的单独测试用例和一个单独的 python 脚本,其中包含针对您在我正在测试的应用程序中可能收到的各种错误消息的不同函数。如果其中一个验证失败,我希望该函数增加一个失败变量,然后主测试脚本将检查它是通过还是失败。

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

这是一个经过大量编辑的示例,说明了在何处使用验证:

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", "")

测试没有正确地增加 failures 变量,我收到错误:未定义名称“failures”,但我不确定在哪里定义它。

最佳答案

您在 ErrorValidations 中声明了一个类属性“failures”,而不是全局属性

而不是使用全局失败尝试:

class ErrorValidations:
failures = 0

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

真正的全局将在类之外声明

关于未定义 Python 全局变量 - 在类内部声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40134743/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com