在 python 中,我如何 use/manipulate 从导入模块中定义的函数中定义脚本中的对象?

In python how can I use/manipulate an object defined in a script from a function defined in an imported module?

这可能是一个非常简单的问题,但我不知道 "right" 答案是什么。假设我有一个脚本

import utils
bar = 1
utils.foo()
print bar

此外,模块utils是:

def foo():
  bar = bar+1

如上所述,我显然得到:

UnboundLocalError: local variable 'bar' referenced before assignment

如何在 foo() 中使用 bar 在我的具体情况下,我真的不想改变 foo,但是我 do 需要能够在 foo().

中使用它和它的状态

一种解决方法是将 bar 传递给 foo():

def foo(bar):
    return bar+1

并替换脚本中的第三行:bar = utils.foo(bar).

但是,这感觉像是一个麻烦的解决方案;特别是如果 bar 是一个复杂的对象。

我对上述案例的最佳实践方法感兴趣。

你为什么不想改变 foo?如果你导入一个模块,你想使用它的功能。如果 foo 函数没有参数,那么 bar 或其中的其他变量将在模块 utils 本身中使用。如果要使用具有不在模块内部的值的函数,则:

def foo(bar):
    return bar+1

完全可以接受。

编辑: // 创建 class foo1 时,只需在构造函数中设置 bar。 class foo1: def init(self, bar): self.bar = 栏

想象一下这种情况:

import someModule

# now you want to use a function of this module
foo()

也许那时会出现这样的错误:bar is not defined or whatever --> modules are not loosely coupled。按照您建议的参数创建函数 foo(完全可以接受),或者通过构造函数或 setBar 方法设置 bar 值。

I am interested in a best-practice approach the case described above

如您所述,barfoo 的参数,将参数传递给函数的最佳实践方法是将其作为参数传递给函数。

utils.py 中:

def foo(bar):
    return bar+1

在您的其他脚本中:

import utils
bar = 1
bar = utils.foo(bar)
print bar

最佳实践方法。它遵循正确的语义。它也是可测试的:

import unittest
import utils

class MyTest(unittest.TestCase):

    def setUp(self):
        self.bar = 1

    def test_bar(self):
        self.assertEquals(2, utils.foo(self.bar))