python - What is the difference between "import package" versus "from package import ..."?
问题描述
Why are some packages such as Pandas always imported as:
import <name of package> #e.g. import pandas as pd
While other packages are "imported" as:
from <name of package> import <module> #e.g. from fredapi import Fred
I understand that when you want to import packages that have a lot of modules, you can import a specific module you need with
from <name of package> import <module> #e.g. from fredapi import Fred
versus importing the entire package and all it's modules.
My question is more about the packages that are only able to imported with:
from <name of package> import <module> #e.g. from fredapi import Fred
Is it because of the structure of the package? Is it because it's not actually a package? I'm confusing myself at this point. Hope someone could shed some light on this.
A concrete example, I can never import fredapi like this:
import fredapi
I can only use fredapi with the "from" command.
from fredapi import Fred
解决方案
将包想象成一个书架,其中包含一些您想阅读的书籍。
您可以选择一次阅读所有内容:
import bookshelf
# read bookshelf.book1, bookshelf.book2, until bookshelf.bookN
或者你可以一次挑几本书来读,
from bookshelf import book1, book5, bookN
在这两种情况下要注意的是,无论您如何阅读书籍,整个书架仍然占据您的书房空间。在 Python 世界中,这意味着无论是导入整个包,还是仅将选择的几个模块导入命名空间,都必须导入整个模块并将其保存在内存中。
推荐阅读
- python-3.x - 从另一个数据框中创建一个数据框中的列不会传输丢失的行
- pandas - plt 不会增加绘图的大小
- mysql - 从 SQL 表中获取 LIMIT 值
- php - 在 PHP 和 sql server 2016 中使用 PDO 出现“找不到驱动程序”错误
- php - 将 äöü 等特殊字符转换为 aou (iconv)
- php - 实现mysqli连接的最佳实践/最实用的方法
- html - 绝对位置时如何在引导程序4中设置mr-0
- python - 我应该如何使用 python 脚本将用户名和密码传递给 Cassandra
- vue.js - Vue中的浅安装,存根不起作用
- movilizer - 如何禁用 Movilizer 表列中的排序