gpt4 book ai didi

python - 在 Python 中,为什么我不能执行 : import A; A. B.C.foo()

转载 作者:太空宇宙 更新时间:2023-11-04 10:54:32 27 4
gpt4 key购买 nike

换句话说,要使用 foo,我需要将所有内容导入 foo,例如:

from A.B.C import foo

或至多

from A.B import C
C.foo()

但是我做不到:

from A import B
B.C.foo()

这给了我类似 'module' object has no attribute "C" 的东西。

最佳答案

文档解释了原因:http://docs.python.org/tutorial/modules.html

Each module has its own private symbol table, which is used as the global symbol table by all functions defined in the module. Thus, the author of a module can use global variables in the module without worrying about accidental clashes with a user’s global variables. On the other hand, if you know what you are doing you can touch a module’s global variables with the same notation used to refer to its functions, modname.itemname.

http://docs.python.org/tutorial/classes.html#python-scopes-and-namespaces :

Strictly speaking, references to names in modules are attribute references: in the expression modname.funcname, modname is a module object and funcname is an attribute of it. In this case there happens to be a straightforward mapping between the module’s attributes and the global names defined in the module: they share the same namespace!

所以简单地说,B.C 没有被导入,并且在上一个例子中也不知道。但这会起作用:

from A import B.C
B.C.foo()

关于python - 在 Python 中,为什么我不能执行 : import A; A. B.C.foo(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11024164/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com