对进口和逃避感到困惑

编程入门 行业动态 更新时间:2024-10-22 15:42:59
对进口和逃避感到困惑 - Python(Confused about imports and evals — Python)

假设我们有两个脚本,script1和script2。

script1定义为:

class Foo(object): def __init__(self, name): self.name = name class bar(object): def __init__(self, name): self.name = name def test(givenString): return eval(givenString)

和script2定义为:

from .script1 import test x = "Foo('me')" print test(x)

script2的test(x) print语句成功告诉我我有一个Foo对象,但这对我没有意义,因为我只从script1导入test ,而不是Foo 。 我查看了eval文档,但这对我来说并不是很清楚。 即使我从未导入类Foo如何创建Foo对象?

Say we have two scripts, script1 and script2.

script1 is defined as:

class Foo(object): def __init__(self, name): self.name = name class bar(object): def __init__(self, name): self.name = name def test(givenString): return eval(givenString)

and script2 is defined as:

from .script1 import test x = "Foo('me')" print test(x)

script2's print statement for test(x) successfully tells me that I have a Foo object, but that doesn't make sense to me because I only imported test from script1, not Foo. I looked at the eval documentation but that didn't clear up much for me. How is it possible that a Foo object is created even when I never imported the class Foo?

最满意答案

eval()使用它执行的模块的全局变量。在script1全局命名空间中test 'lives',因此eval()执行的任何表达式都使用与该函数相同的命名空间,因此可以解析Foo , bar和test 。

导入函数不会改变其命名空间; test的全局变量不会仅仅通过从script2调用而script2 。 如果是这样,那么script1任何导入都需要导入到script2 ,用于您想要使用的每个函数。 这将是非常不切实际的。

您甚至可以看到导入函数的全局变量; print test.func_globals将显示script1的确切命名空间。

eval() uses the globals of the module it is executed in. test 'lives' in the script1 global namespace, so any expression executed by eval() uses the same namespace as that function and thus can resolve Foo, bar and test.

Importing a function does not alter its namespace; the globals for test don't change merely by being called from script2. If it did, any imports in script1 would also need to be imported into script2, for each and every function you ever wanted to use. That would be incredibly impractical.

You can even see the globals for functions you import; print test.func_globals will show you the exact namespace of script1.

更多推荐

本文发布于:2023-08-06 23:33:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1456608.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:困惑

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!