赋值前引用的局部变量/Python

2024-04-26 22:54:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试设计一个计数器,它将在每次操作完成时递增。像这样:

def action_on_accounts(self, accounts):
    for account in accounts[9:]: 
        try:
            self.browser.get(account)
            time.sleep(5)
            action_button = self.browser.find_element_by_xpath(u'//button[contains(@class, "Heart")]').click()
            counter_var = self.count_actions(counter_var)
            print(counter_var)
        except selenium.common.exceptions.NoSuchElementException:
            break

def count_actions(self, counter_var):
    return counter_var + 1

def main(self):

    counter_var = 0
    (...)

这是抛出一个UnboundLocalError: local variable 'counter_var' referenced before assignment

我已经读到我必须将counter_var声明为全局内部函数,并执行了以下操作:

^{pr2}$

它在投掷SyntaxError: name 'counter_var' is parameter and global error。在

所以我试了一下:

def count_actions(self):
    global counter_var
    return counter_var + 1

这样说:

counter_var = self.count_actions()
print(counter_var)

现在我有了NameError: name 'counter_var' is not defined。。。。在

请协助


Tags: nameselfbrowseractionsreturnisvardef
3条回答

另一种更简单的解决方案是使用python的内置enumerate();它的存在使我们不必创建自己的函数。然后,可以将计数设置为在函数外部声明的全局变量

所以代码应该是这样的:

counter_var = 0
def action_on_accounts(self, accounts):
    for count, account in enumerate(accounts[9:]): 
            global counter_var
            counter_var = count
            print(counter_var)

def main(self):
    global counter_var
    counter_var = 0
    (...)

如果你真的想使用一个全局变量(我建议你反对),你可以用global关键字来实现。您需要该关键字来声明变量。示例:

def action_on_accounts():
    global counter_var #declare the variable
    counter_var = count_actions(counter_var)
    print(counter_var)

def count_actions(cv):
    global counter_var  #you do not have to declare the variable here since we are theoretically in the right scope
    print(counter_var) #just to check that is global
    return cv + 1 #no need to declare since it is a parameter

if __name__ == "__main__":
    counter_var = 0
    action_on_accounts() #1
    action_on_accounts() #2
    print(counter_var) #will return 2

我在IPython控制台(python3.6)中对此进行了测试。在

但是,我强烈建议您使用类的属性来实现相同的效果(就像使用self而不是global)。全局变量可能会创建错误代码。在

您应该考虑将counter_var定义为属性:self.counter_var。你的整个班级都可以访问它(假设是这样的)。您不必在函数/方法中显式地提供它作为参数,也不必担心全局变量。在

def action_on_accounts(self, accounts):
    for account in accounts[9:]: 
        try:
            self.browser.get(account)
            time.sleep(5)
            action_button = self.browser.find_element_by_xpath(u'//button[contains(@class, "Heart")]').click()
            self.count_actions()
            print(self.counter_var)
        except selenium.common.exceptions.NoSuchElementException:
            break

def count_actions(self):
    self.counter_var += 1

def main(self):

    self.counter_var = 0
    (...)

不过,您可能需要用类初始化self.counter_var。在

相关问题 更多 >