如何在Python脚本中为导入的类获取相同的作用域?

2024-03-29 09:35:39 发布

您现在位置:Python中文网/ 问答频道 /正文

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

在文件中食品公司名称:

class foo(object):
    def __init__(self):
        print globals()

在我的主文件中:

^{pr2}$

为什么返回的foo-bar和global列表不同?在

因为任何需要访问main 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)

(这一切的工作方式不是我的选择,除非我有时间使用应用程序开发人员:-)


Tags: 文件self脚本hereobjectfooinitdef
1条回答
网友
1楼 · 发布于 2024-03-29 09:35:39

下面是python3FAQ要说的:

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文件中分配的所有名称都可以在包命名空间中使用。在

相关问题 更多 >