从其他纸条递增整数

2024-03-29 10:58:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图理解如何访问和递增驻留在另一个脚本中的整数。我的等级是这样的:

- TestDirectory
-- foo.py
-- bar.py

示例:

foo.py公司

import TestDirectory.bar as bar
def main():
    testCounter = 0
    bar.increment()
    print(testCounter)

main()

棒.py

import TestDirectory.foo as foo
def increment():
    foo.main().testCounter += 1

我希望打印结果返回1,但它给了我一个错误:

AttributeError: module 'TestDirectory' has no attribute 'bar'

有人能解释或解决我的问题吗?你知道吗


Tags: pyimport脚本示例foomaindefas
3条回答

发布我的解决方案来帮助任何需要帮助的人!你知道吗

层次结构是这样的(尽管这不重要):

- Folder1
  bar.py
- Folder2
  foo.py

解决方案:

foo.py公司

from Folder1 import bar
def main():
    bar.increment()
    print(bar.counter)

main()

棒.py

counter = 0
def increment():
    global counter
    counter += 1

虽然我无法重现你的错误(这没关系),但你似乎在这里被搞砸了。你知道吗

在您的案例中,绕过循环问题的简单方法如下:

  • bar.py中,修改increment函数的行为,将int作为输入参数,并在更新后返回。你知道吗
  • foo.py中,更新main以将testCounter作为参数发送并捕获其返回值。你知道吗
  • 纠正foo.py中的import语句(取决于您的约定),同时删除bar.py中的循环导入。你知道吗

以下是我为解决这个问题所做的最低限度的代码更改。
注意:从TestDirectory文件夹中运行。你知道吗

foo.py公司

import bar

def main():
    testCounter = 0
    testCounter = bar.increment(testCounter)
    print(testCounter)

main()

棒.py

def increment(testCounter):
    testCounter += 1
    return testCounter

你的代码有很多问题:

  1. 方法中的变量是方法的本地变量,您不能从函数外部访问它们,忘记脚本外部的变量(即模块)
  2. 要在同一文件夹中导入另一个模块,只需使用脚本本身的名称
  3. 由于您希望从bar访问foo,并且从foo访问bar,因此您最终会得到一个循环导入,本地导入可以避免这种情况

这里有一个解决你问题的方法,但很可能,你会做得更好的设计更改,而不是我所提供的:

你知道吗foo.py公司你知道吗

import bar

testCounter=0

if __name__=="__main__":
    bar.incrementTestCounter()
    print bar.getTestCounterValue()

你知道吗棒.py你知道吗

def incrementTestCounter():
    import foo
    foo.testCounter=foo.testCounter+1

def getTestCounterValue():
    import foo
    return foo.testCounter

相关问题 更多 >