在python中导入模块时如何避免一直写出模块的名称? [英] How to avoid writing the name of the module all the time when importing a module in python?

查看:264
本文介绍了在python中导入模块时如何避免一直写出模块的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近使用了 math 模块。我不想一直写 math.sqrt(x) math.sin(x)。我想缩短它并编写 sqrt(x) sin(x)
如何?

I use the math module a lot lately. I don't want to write math.sqrt(x) and math.sin(x) all the time. I would like to shorten it and write sqrt(x) and sin(x). How?

推荐答案

对于较长的模块名称,通常会缩短它们,例如

For longer module names it is common to shorten them, e.g.

import numpy as np

然后你可以使用短名称。或者你可以导入你需要的特定东西,如其他的anwsers所示:

Then you can use the short name. Or you can import the specific stuff that you need, as shown in the other anwsers:

from math import sin, sqrt

这通常用在包内,用于更紧密耦合的代码。对于图书馆,名称缩短的第一个选项通常是首选方式。

This is often used inside packages, for code that is more closely coupled. For libraries the first option with the name shortening is often the prefered way.

从不做的是使用来自math import * 表格。它会污染名称空间,可能导致名称冲突并使调试更加困难。最重要的是,它使代码难以阅读,因为不清楚特定函数的来源。

What you should never do is use the from math import * form. It will pollute the name space, potentially leading to name collisions and making debugging harder. Most importantly it makes the code hard to read, because it is not clear where a particular function came from.

可以在交互式解释器中进行异常。但是,一旦你习惯使用缩短的名字,就可能不值得去那里使用其他约定。

An exception can be made in the interactive interpreter. But once you are in the habit of using the shortened names it might not be worth to go with another convention there.

这篇关于在python中导入模块时如何避免一直写出模块的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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