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