脚本中定义的类似乎与导入到脚本中的类具有不同的作用域。例如:
在文件 foo.py 中:
class foo(object):
def __init__(self):
print globals()
在我的主文件中:
from foo import foo
class bar(object):
def __init__(self):
print globals()
classimport = foo()
classinternal = bar()
从 foo 和 bar 返回的全局变量列表不同 - 这是为什么?
这让生活变得困难,因为任何需要访问主 globals() 的类都必须驻留在主文件中。如何确保导入的类具有相同的全局作用域?我在阅读其他帖子后尝试过的一些事情here和 here包括:
module = __import__("foo", fromlist="foo")
globals()["foo"] = getattr(module, "foo")
和
__builtin__.foo = foo
感谢任何帮助!
[编辑] ---
因此,根据上面的链接,这个问题在 duplicate article 中得到了回答。 。事实证明,范围并不跨模块共享。它提到了解决此问题的几种方法,但就我而言,我需要实际创建/读取/写入全局变量。因此,我在主脚本中创建了一个例程,并在初始化 foo 和 bar 时将其作为对象传递。例如:
def PrintGlobals():
print globals()
class bar(object):
def __init__(self, PrintGlobals):
self.PrintGlobals = PrintGlobals
self.PrintGlobals()
classinternal = bar(PrintGlobals)
(这不是我选择的,这只是一个黑客,直到我有时间与应用程序开发人员一起工作:-)
最佳答案
这是 Python 3 FAQ 的内容不得不说:
In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.
Though a bit surprising at first, a moment’s consideration explains this. On one hand, requiring global for assigned variables provides a bar against unintended side-effects. On the other hand, if global was required for all global references, you’d be using global all the time. You’d have to declare as global every reference to a built-in function or to a component of an imported module. This clutter would defeat the usefulness of the global declaration for identifying side-effects.
要查看不同范围内的全局变量,请尝试在执行期间的不同点执行 print(globals()) 。例如:在运行任何代码之前的顶级模块,然后在 __init__.py
中,如果其中有任何代码(因为导入 foo),在 foo 的模块级别,在每个函数内,以及修改传递给函数的任何变量之前/之后。
This answer进一步解释:
I think the key thing you're missing here is that each module has its own "global" namespace. This can be a bit confusing at first, because in languages like C, there's a single global namespace shared by all external variables and functions. But once you get past that assumption, the Python way makes perfect sense.
但请注意,当您导入包或包中的模块时,包 __init__.py
文件中分配的所有名称都可以在包命名空间中使用。
关于python - 如何在 Python 脚本中获得导入类的相同作用域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33790642/