Python 从其他脚本递增整数
我试图理解如何访问和增加驻留在另一个脚本中的整数。我的等级是这样的:Python 从其他脚本递增整数,python,Python,我试图理解如何访问和增加驻留在另一个脚本中的整数。我的等级是这样的: - TestDirectory -- foo.py -- bar.py 例如: foo.py import bar def main(): testCounter = 0 testCounter = bar.increment(testCounter) print(testCounter) main() bar.py import bar def main(): testCounter
- TestDirectory
-- foo.py
-- bar.py
例如:
foo.py
import bar
def main():
testCounter = 0
testCounter = bar.increment(testCounter)
print(testCounter)
main()
bar.py
import bar
def main():
testCounter = 0
testCounter = bar.increment(testCounter)
print(testCounter)
main()
我希望打印结果返回1,但它给了我一个错误:
AttributeError: module 'TestDirectory' has no attribute 'bar'
有人能解释或解决我的问题吗 虽然我无法重现您的错误(这无关紧要),但您似乎在这里的循环导入中被搞砸了 在您的案例中,绕过循环问题的简单方法如下:
- 在
中,修改bar.py
函数的行为,将increment
作为输入参数,并在更新后返回int
- 在
中,更新foo.py
以将main
作为参数发送并捕获其返回值testCounter
- 更正
中的导入语句(取决于您的惯例),同时删除foo.py
中的循环导入bar.py
注意:从
TestDirectory
文件夹中运行
foo.py
import bar
def main():
testCounter = 0
testCounter = bar.increment(testCounter)
print(testCounter)
main()
bar.py
def increment(testCounter):
testCounter += 1
return testCounter
您的代码有很多问题:
bar
访问foo
,并从foo
访问bar
,因此最终会出现循环导入,本地导入可以避免这种情况import bar
testCounter=0
if __name__=="__main__":
bar.incrementTestCounter()
print bar.getTestCounterValue()
巴比
def incrementTestCounter():
import foo
foo.testCounter=foo.testCounter+1
def getTestCounterValue():
import foo
return foo.testCounter
发布我的解决方案以帮助其他需要帮助的人 等级制度是这样的(尽管这不重要): 解决方案: foo.py
import bar
def main():
testCounter = 0
testCounter = bar.increment(testCounter)
print(testCounter)
main()
bar.py
import bar
def main():
testCounter = 0
testCounter = bar.increment(testCounter)
print(testCounter)
main()
无论如何,这不会起作用。但我认为您面临的问题是循环导入。除了循环导入的问题外,我无法重现此错误。我得到了一个
导入错误:当我尝试从外部运行它时,没有名为“TestDirectory”的模块。TestDirectory
。但是您知道如何解决此问题吗?您不知道吗只需将testCounter
作为参数传递给increment()
?因此,如果要在foo脚本中删除bar的导入,如何从bar脚本中增加整数?
counter = 0
def increment():
global counter
counter += 1