【发布时间】:2015-10-20 15:15:40
【问题描述】:
这可能是一个非常幼稚的问题,也许最好用一个例子来问:
module1.py
import module2
def new_func():
print(var_string)
module2.new_func = new_func
module2.func()
module2.new_func()
module2.py
var_string = "i'm the global string!"
def func():
print(var_string)
结果
> python module1.py
i'm the global string!
Traceback (most recent call last):
File "module1.py", line 8, in <module>
module2.new_func()
File "module1.py", line 4, in new_func
print(var_string)
NameError: name 'var_string' is not defined
所以我的问题是: 是否可以将函数插入模块并相应地更新其全局命名空间?
相关:global variable defined in main script can't be accessed by a function defined in a different module 请注意,我知道共享全局变量是一个坏主意,而且我也知道配置模块将是一个很好的折衷方案,但也请注意,这不是我想要实现的目标。
【问题讨论】:
-
他们没有必要这样做。您可以只使用 if 语句来确定调用哪个方法,或者将哪些参数传递给方法。等等……
-
我不同意。我认为这将非常有用。类比是向现有类动态添加一个方法,该类利用该类的其他属性和方法。我还希望这个插入的函数可以被其他模块调用。本质上,我是在动态扩展模块,而不需要对模块的源代码进行物理编辑。
-
你需要把 print(var_string) 改成 print(module2.var_string)
-
@DamiánMontenegro 不,这不是我要找的。我希望 func 可以直接访问 module2 的全局成员,就好像它最初是在 global2 中定义的一样。
-
我从来没有这样做过。但是方法是否覆盖了您所说的内容?看看这个链接lgiordani.com/blog/2014/05/19/method-overriding-in-python/…
标签: python module global-variables