import module VS from module import *

Importing. What are the differences between using "import module" and "from module import *"? 

import module是最基本的导入语句,其作用是将一个模块导入当前的名字空间中,当需要该模块的一个属性或者方法及类时,必须通过模块的名称空间来获取。 

from module import *是对from module import 语句的增强,后者是将一个制定的名字导入到当前名字空间,前者是将模块中所有的可见元素的名字都导入当前名称空间。因为from module import语句的副作用是: 

   如果当前名称空间有一个元素的名字与被导入元素的名字同名,那这个元素将被后者覆盖 

由此可知,from module import * 是及其危险的,如果不慎重使用,可能会导致当前名字空间的大量元素被偷梁换柱。 

《Python core programming》中有这么一段话: 
引用
In practice, using from module import * is considered poor style because it "pollutes" the current namespace and has the potential of overriding names in the current namespace; however, it is extremely convenient if a module has many variables that are often accessed, or if the module has a very long name.

We recommend using this form in only two situations. The first is where the target module has many attributes that would make it inconvenient to type in the module name over and over again. Two prime examples of this are the Tkinter (Python/Tk) and NumPy (Numeric Python) modules, and perhaps the socket module. The other place where it is acceptable to use from module import * is within the interactive interpreter, to save on the amount of typing.


翻译下来就是: 
实际上,使用 from module import * 被认为是一个不好的风格,因为这种做法会“污染”当前名称空间,并有可能会覆盖掉当前域名空间中的名字。但另一方面,这种做法又具有极大的便利性,尤其在module很有多变量经常被使用或者module的名字非常长。 

我们建议只在两种情况下使用该方式: 
1.目标模块有太多属性,而该模块需要频繁使用,这样就会显得麻烦。Tkinter(Python/Tk)与NumPy(Numeric Python)模块就是两个例子,或许socket模块也是。 
2.另一个场所就是在交互式解释器上,使用from module import * 可以节省很多敲击的力气
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值