python - 如何在 Python 脚本中获得导入类的相同作用域?

标签 python python-2.7 scope python-import global-scope

脚本中定义的类似乎与导入到脚本中的类具有不同的作用域。例如:

在文件 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() 的类都必须驻留在主文件中。如何确保导入的类具有相同的全局作用域?我在阅读其他帖子后尝试过的一些事情herehere包括:

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/

相关文章:

python - 将 ImageField 的内容复制到 Django 中的新文件路径

python - 如下应用 SLIC 后如何检测云的百分比?

python - PyInstance_NewRaw() 与新旧样式类

javascript - 在 Javascript 中,为什么从构造函数返回一个函数会破坏对象?

python - 所以我想用 Python 制作一个时钟来显示上午和下午。和下午

python - 如何合并 Django Admin Mixins 中的功能?

python - 在 Python 中使用的高级邮件

python - 窗口框架中的标签不会拉伸(stretch),为什么?

javascript - 查看复杂对象变量 (objectVar.some.other.value) 是否已定义的简单方法

java - 带有自定义对象数组列表的 Java 中的变量范围问题