我有一个名为myGlobal.py
的python文件,在这个文件中我将count
声明为全局变量。
import datetime
import time
import os
count = 0
failCount = 0
def counterstart:
global count
count +=1
我在另一个文件中调用此计数器。因此,每次调用函数时,我都希望计数器增加1.该文件为scripts.py
import os
from selenium import webdriver
import datetime
import time
from myGlobal import *
def main():
fnfirst()
fnsecond()
fnthird()
def fnfirst():
global count
print count
def fnsecond():
global count
print count
def fnthird():
global count
print count
main()
但每当我运行script.py
时,计数仅显示为0。
为什么会这样?
答案 0 :(得分:0)
import myGlobal
print myGlobal.count # 0
myGlobal.count += 1
def foo():
myGlobal.count += 1
foo()
print myGlobal.count # 2
所以这是一个基于Python的装饰器的解决方案。它将计算特定函数的调用次数:
# File script.py
import myGlobal
def count_call(func):
def _wrapper(*args, **kwargs):
myGlobal.count += 1
func(*args, **kwargs)
return _wrapper
@count_call
def fnfirst():
pass # do something
@count_call
def fnsecond():
pass # do something
def main():
print myGlobal.count # 0
fnfirst()
print myGlobal.count # 1
fnsecond()
print myGlobal.count # 2
fnfirst()
print myGlobal.count # 3
if __name__ == "__main__":
main()