[英]In python how can I use/manipulate an object defined in a script from a function defined in an imported module?
This might be a terribly simple one, but I don't know what's the "right" answer. 这可能是一个非常简单的答案,但我不知道“正确”的答案是什么。 Assume that I have a script 假设我有一个脚本
import utils
bar = 1
utils.foo()
print bar
Furthermore, the module utils
is: 此外,模块utils
是:
def foo():
bar = bar+1
As given above, I ,obviously, get: 如上所述,显然,我得到:
UnboundLocalError: local variable 'bar' referenced before assignment
How can I use bar
inside foo()
? 如何在foo()
使用bar
? In my specific case, I don't really want to alter foo
, but I do need to be able to use it and its state inside foo()
. 在我的特定情况下,我并不是真的想要更改foo
,但是我确实需要能够在foo()
使用它及其状态。
One workaround would be to pass bar
to foo()
: 一种解决方法是将bar
传递给foo()
:
def foo(bar):
return bar+1
And replace the third line in the script: bar = utils.foo(bar)
. 并替换脚本中的第三行: bar = utils.foo(bar)
。
However, this feels like a cumbersome solution; 但是,这感觉很麻烦。 in particular if bar is a complex object. 特别是如果bar是一个复杂的对象。
I am interested in a best-practice approach the case described above. 我对上述案例的最佳实践方法感兴趣。
Why don't you want to alter foo? 您为什么不想更改foo? If you import a module, you want to use its functionality. 如果导入模块,则要使用其功能。 If the foo function is without parameters, then bar or other variables in it are used in the module utils itself. 如果foo函数没有参数,则在模块utils本身中使用bar或其他变量。 If you want to use a function with values that are not inside the module, then: 如果要使用功能值不在模块内部的函数,则:
def foo(bar):
return bar+1
is totally acceptable. 是完全可以接受的。
EDIT: // When you create class foo1, just set bar in the constructor. 编辑://创建类foo1时,只需在构造函数中设置bar。 class foo1: def init (self, bar): self.bar = bar 类foo1:def init (self,bar):self.bar = bar
Image this situation: 图片这种情况:
import someModule
# now you want to use a function of this module
foo()
Maybe then there would be an error like: bar is not defined or whatever --> modules are not loosely coupled. 也许然后会出现类似以下错误:未定义bar或任何->模块未松耦合。 Either make the function foo as you proposed with parameters (totally acceptable) or set the bar value via a constructor or setBar method. 根据您的建议使用参数使函数foo(完全可以接受),或者通过构造函数或setBar方法设置bar值。
I am interested in a best-practice approach the case described above 我对上述案例的最佳实践方法感兴趣
As you describe, bar
is an argument to foo
, and the best practice way to pass an argument to a function is to pass it as an argument to the function. 正如您所描述的, bar
是foo
的参数,将参数传递给函数的最佳实践是将其作为参数传递给函数。
in utils.py
: 在utils.py
:
def foo(bar):
return bar+1
And in your other script: 在您的其他脚本中:
import utils
bar = 1
bar = utils.foo(bar)
print bar
This is the best practice approach. 这是最佳做法。 It follows the correct semantics. 它遵循正确的语义。 It is also testable: 这也是可测试的:
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.