gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:45:26 25 4
gpt4 key购买 nike

我正在尝试设计一个计数器,每次执行操作时该计数器都会增加。像这样:

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声明为全局内部函数,并执行以下操作:
def count_actions(self, counter_var):
global counter_var
return counter_var + 1

它正在抛出 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...。

请协助

最佳答案

您应该考虑将counter_var定义为属性:self.counter_var。在整个类(class)中都可以访问它(假设正在发生这种情况)。您无需在函数/方法中显式提供它作为参数,也不必担心全局变量。

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

关于python - 赋值之前引用的局部变量/Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53972180/

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