我正在尝试设计一个计数器,每次执行操作时该计数器都会增加。像这样:
currentUserImageContainerStyle:{
minHeight:24,
position: 'absolute',
bottom:0,
right:0,
zIndex: 1,
}
这会抛出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)
....
请协助
答案 0 :(得分: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
(...)
答案 1 :(得分:2)
您应该考虑将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
。
答案 2 :(得分:1)
好吧,如果您确实要使用全局变量(我建议反对),则可以使用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控制台(Python 3.6)中对此进行了测试。
但是,我强烈建议您使用类的属性来达到相同的效果(如在使用self而不是global时一样)。全局变量可能会创建错误的代码。