为什么Python的导入不能像C的#include一样工作? [英] Why can't Python's import work like C's #include?

查看:158
本文介绍了为什么Python的导入不能像C的#include一样工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实际上已经尝试了解大约一年的Python导入,而且我几乎放弃了Python中的编程,因为它似乎太混淆了。我来自C背景,我假设 import #include 一样工作,但是如果我尝试导入某些东西,我总是得到错误。

I've literally been trying to understand Python imports for about a year now, and I've all but given up programming in Python because it just seems too obfuscated. I come from a C background, and I assumed that import worked like #include, yet if I try to import something, I invariably get errors.

如果我有两个这样的文件:

If I have two files like this:

foo.py:

a = 1

bar.py:

import foo
print foo.a
input()

为什么我需要引用模块名称?为什么不能只写 import foo 打印?这种混乱有什么意义?为什么不运行代码并为您定义的东西,就像您在一个大文件中编写它一样?为什么它不能像C的#include指令一样工作,它基本上复制和粘贴你的代码?我在C中没有导入问题。

WHY do I need to reference the module name? Why not just be able to write import foo, print a? What is the point of this confusion? Why not just run the code and have stuff defined for you as if you wrote it in one big file? Why can't it work like C's #include directive where it basically copies and pastes your code? I don't have import problems in C.

推荐答案

要做你想做的事,你可以使用(不推荐,进一步阅读)解释):

To do what you want, you can use (not recommended, read further for explanation):

from foo import *

这会将所有内容导入您当前的命名空间,您可以调用打印

This will import everything to your current namespace, and you will be able to call print a.

然而,这种方法的问题如下。考虑这种情况,当你有两个模块, moduleA moduleB ,每个模块都有一个名为的函数GetSomeValue()
当你这样做:

However, the issue with this approach is the following. Consider the case when you have two modules, moduleA and moduleB, each having a function named GetSomeValue(). When you do:

from moduleA import *
from moduleB import *

你有一个名称空间解析问题*,因为你用 GetSomeValue()实际调用了什么函数 moduleA.GetSomeValue() moduleB.GetSomeValue()

you have a namespace resolution issue*, because what function are you actually calling with GetSomeValue(), the moduleA.GetSomeValue() or the moduleB.GetSomeValue()?

除此之外,您还可以使用导入为功能:

In addition to this, you can use the Import As feature:

from moduleA import GetSomeValue as AGetSomeValue
from moduleB import GetSomeValue as BGetSomeValue

import moduleA.GetSomeValue as AGetSomeValue
import moduleB.GetSomeValue as BGetSomeValue

此方法可手动解决冲突。

This approach resolves the conflict manually.

我相信你可以从这些例子中了解显式引用的必要性。

I am sure you can appreciate from these examples the need for explicit referencing.

* Python有其命名空间解决机制,这只是为了解释的简化。

* Python has its namespace resolution mechanisms, this is just a simplification for the purpose of the explanation.

这篇关于为什么Python的导入不能像C的#include一样工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆