在Python中导入模块 - 最佳实践 [英] Importing modules in Python - best practice

查看:222
本文介绍了在Python中导入模块 - 最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的Python,因为我想扩展我学习使用R的技能。
在RI倾向于加载一堆库,有时导致函数名冲突。



Python中的最佳实践是什么?我看到一些具体的变化,我没有看到之间的区别



import pandas from pandas import * from pandas import DataFrame



之间的前两个,我应该只导入我需要的东西。
此外,对于使小程序处理数据和计算简单统计信息的人而言,最糟糕的后果是什么。



UPDATE p>

我发现这个优秀指南

解决方案

import pandas pandas命名空间,所以你需要使用 pandas.foo 来调用pandas中的对象。



from pandas import * 将所有对象从pandas模块导入到当前命名空间中,因此只需使用 foo 即可调用pandas中的对象。请记住,如果您当前的命名空间和pandas命名空间之间存在任何命名冲突,这可能会产生不可预测的后果。



来自pandas import DataFrame 与上述相同,但只导入 DataFrame (而不是一切)到你当前的命名空间。



在我看来,第一个是一般的最佳实践,因为它保持不同的模块很好地划分在你的代码。


I am new to Python as I want to expand skills that I learned using R. In R I tend to load a bunch of libraries, sometimes resulting in function name conflicts.

What is best practice in Python. I have seen some specific variations that I do not see a difference between

import pandas, from pandas import *, and from pandas import DataFrame

What are the differences between the first two and should I just import what I need. Also, what would be the worst consequences for someone making small programs to process data and compute simple statistics.

UPDATE

I found this excellent guide. It explains everything.

解决方案

import pandas imports the pandas module under the pandas namespace, so you would need to call objects within pandas using pandas.foo.

from pandas import * imports all objects from the pandas module into your current namespace, so you would call objects within pandas using only foo. Keep in mind this could have unexepcted consequences if there are any naming conflicts between your current namespace and the pandas namespace.

from pandas import DataFrame is the same as above, but only imports DataFrame (instead of everything) into your current namespace.

In my opinion the first is generally best practice, as it keeps the different modules nicely compartmentalized in your code.

这篇关于在Python中导入模块 - 最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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