为什么必须“导入" Python标准库函数? [英] Why do you have to 'import' Python Standard Library functions?

查看:447
本文介绍了为什么必须“导入" Python标准库函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python编码的新手,并且来自PHP背景.我很好奇为什么必须在python脚本的顶部导入"函数.在PHP中,您可以简单地使用以下功能:

I'm new to Python coding and I'm coming from a PHP background. I'm curious why you have to 'import' functions at the top of you python script. In PHP you can simply use the function such as:

sleep(10);

以上内容将导致脚本休眠10秒钟.但是,要在python中执行相同的操作,似乎我必须导入时间"功能:

The above would cause the script to sleep for 10 seconds. However, to do the same thing in python, it seems I have to import the 'time' functionality:

import time
time.sleep(10)

我的问题是:为什么这是必要的?如果这些额外的功能已经是python的一部分,为什么python必须专门加载它们?在PHP中,如果缺少模块,脚本将失败.我必须在全局安装该模块,然后才能正常使用.

My question is: why is this necessary? If these extra functions are part of python already, why does python have to specifically load them? In PHP, if a module is missing, the script fails. I have to install the module globally and then it's usable like normal.

python的方法是否有优势?

Is there an advantage to python's approach?

推荐答案

是的,有几个.这意味着默认情况下编译和运行的内容更少.您的程序将加载得更快,因为它只知道它实际需要的Python部分.

Yes, several. It means that there is less to compile and run by default. Your program will load faster, because it only knows about the parts of Python that it actually needs.

它使全局名称空间保持整洁,并允许将功能按逻辑分组到模块中.不同的模块可以具有名称相同的功能而不会发生冲突(例如,文件和套接字类可能同时具有打开和关闭功能).

It keeps the global namespace clean, and allows functionality to be grouped logically into modules. Different modules can have identically-named functions without clashes (a file and socket class would probably both have open and close functions, for example).

这篇关于为什么必须“导入" Python标准库函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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