导入语句 python_Python导入语句说明

导入语句 python

While learning programming and reading some resources you’d have come across this word ‘abstraction’ which simply means to reduce and reuse the code as much as possible.

在学习编程和阅读一些资源时,您会遇到“抽象”一词,这意味着尽可能地减少和重用代码。

Functions and Modules facilitate abstraction. You create functions when you want to do something repeatedly within a file.

功能和模块有助于抽象。 当您要在文件中重复执行某些操作时,可以创建函数。

Modules come into picture when you want to reuse a group of functions in different source files. Modules are also useful in structuring the program well.

当您想在不同的源文件中重用一组功能时,模块就会出现。 模块也可以很好地构造程序。

  • Using Standard Libraries and other third party modules

    使用标准库和其他第三方模块
  • Structuring the program

    编写程序

使用标准库 (Using Standard Libraries)

Example: You can read about the methods/functions of all the standard libraries in the official Python Docs in detail.

示例:您可以详细阅读官方Python Docs中所有标准库的方法/功能。

import time
for i in range(100):
    time.sleep(1)   # Waits for 1 second and then executes the next command
    print(str(i) + ' seconds have passed')  # prints the number of seconds passed after the program was started

Run Code

运行代码

# To calculate the execution time of a part of program
import time
start = time.time()
# code here
end = time.time()
print('Execution time:' , end-start)

Run Code

运行代码

# Using math Module
import math
print(math.sqrt(100))   # prints 10

Run Code

运行代码

使用第三方模块 (Using third party Modules)

Third party modules don’t come bundled with python , but we have to install it externally using package managers like pip and easy install

第三方模块未与python捆绑在一起,但我们必须使用pipeasy install类的包管理器从外部进行easy install

# To make http requests
import requests
rq = requests.get(target_url)
print(rq.status_code)

Find out more about python-requests module here

在此处找到有关python-requests模块的更多信息

构造程序 (To structure programs)

We want to make a program that has various functions regarding prime numbers. So lets start. We will define all the functions in prime_functions.py

我们要制作一个具有有关质数的各种功能的程序。 因此,让我们开始吧。 我们将在prime_functions.py定义所有功能

# prime_functions.py
from math import ceil, sqrt
def isPrime(a):
    if a == 2:
        return True
    elif a % 2 == 0:
        return False
    else:
        for i in range(3,ceil(sqrt(a)) + 1,2):
            if a % i == 0:
                return False
        return True

def print_n_primes(a):
    i = 0
    m = 2
    while True:
        if isPrime(m) ==True:
            print(m)
            i += 1
        m += 1
        if i == a:
            break

Now we want to use the functions that we just created in prime_functions.py so we create a new file playground.py to use those functions.

现在,我们要使用的功能,我们只需在创建prime_functions.py所以我们创建一个新的文件playground.py使用这些功能。

Please note that this program is far too simple to make two separate files, it is just to demonstrate. But when there are large complex programs, making different files is really useful.

请注意,该程序太简单了,无法创建两个单独的文件,仅用于演示。 但是,当有大型复杂程序时,制作不同的文件确实很有用。

# playground.py
import prime_functions
print(prime_functions.isPrime(29)) # returns True

排序进口 (Sorting Imports)

Good practice is to sort import modules in three groups - standard library imports, related third-party imports, and local imports. Within each group it is sensible to sort alphabetically by module name. You can find more information in PEP8.

优良作法是将import模块分为三类-标准库导入,相关的第三方导入和本地导入。 在每个组中,明智的是按模块名称的字母顺序进行排序。 您可以在PEP8中找到更多信息

One of the most important thing for Python language is legibility, and alphabetically sorting modules are quicker to read and search. Also it is easier to verify that something is imported, and avoid duplicated imports.

对于Python语言来说,最重要的事情之一就是易读性,并且按字母顺序排序的模块可以更快地读取和搜索。 此外,更容易验证是否已导入某些内容,并避免重复导入。

从X导入Y:一个例子 (From X import Y: an example)

Here's an example problem:

这是一个示例问题:

>>> from math import ceil, sqrt
>>> # here it would be
>>> sqrt(36)
<<< 6

Run Code

运行代码

Or we could use this one instead:

或者我们可以改用这个:

>>> import math
>>> # here it would be
>>> math.sqrt(36)
<<< 6

Run Code

运行代码

Then our code would look like math.sqrt(x) instead of sqrt(x). This happens because when we use import x, a namespace x is itself created to avoid name conflicts. You have to access every single object of the module as x.<name>.

然后我们的代码看起来就像math.sqrt(x)而不是sqrt(x) 。 发生这种情况是因为当我们使用import x ,本身会创建一个名称空间x以避免名称冲突。 您必须以x.<name>身份访问模块的每个对象。

But when we use from x import y we agree to add y to the main global namespace. So while using this we have to make sure that we don’t have an object with same name in our program.

但是,当我们from x import y使用时from x import y我们同意将y添加到主要的全局命名空间中。 因此,在使用它时,我们必须确保程序中没有相同名称的对象。

Never use from x import y if an object named y already exists

如果已经存在名为y的对象,请不要from x import y使用

For example, in os module there’s a method open. But we even have a built-in function called open. So, here we should avoid using from os import open.

例如,在os模块中,有一个open方法。 但是我们甚至有一个内置函数open 。 因此,这里我们应该避免使用from os import open

We can even use form x import *, this would import all the methods, classes of that module to the global namespace of the program. This is a bad programming practice. Please avoid it.

我们甚至可以使用form x import * ,这会将所有方法,该模块的类导入程序的全局名称空间。 这是不好的编程习惯。 请避免。

In general you should avoid from x import y simply because of the problems it may cause in large scale programs. For example, you never know if a fellow programmer might want to make a new function that happens to be the name of one of the existing functions. You also do not know whether Python will change the library that you are importing functions from. While these problems won’t exist as often for solo projects, as stated before, it is bad programming practice and should be avoided.

通常,您应该避免from x import y仅仅是因为它可能在大型程序中引起的问题。 例如,您永远都不知道其他程序员是否可能想要创建一个恰好是现有功能之一名称的新功能。 您还不知道Python是否会更改您要从中导入函数的库。 如前所述,虽然这些问题对于单独项目而言并不常见,但是这是不好的编程习惯,应避免使用。

翻译自: https://www.freecodecamp.org/news/python-import-statements/

导入语句 python

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值