导入语句 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 commandprint(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捆绑在一起,但我们必须使用pip
和easy 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 Trueelif a % 2 == 0:return Falseelse:for i in range(3,ceil(sqrt(a)) + 1,2):if a % i == 0:return Falsereturn Truedef print_n_primes(a):i = 0m = 2while True:if isPrime(m) ==True:print(m)i += 1m += 1if 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
相关文章:

网页性能测试---webpagetest
http://www.webpagetest.org/转载于:https://www.cnblogs.com/cai-yu-candice/p/8194866.html

1小时学会:最简单的iOS直播推流(十一)spspps和AudioSpecificConfig介绍(完结)
最简单的iOS 推流代码,视频捕获,软编码(faac,x264),硬编码(aac,h264),美颜,flv编码,rtmp协议,陆续更新代码解析,你想学的知识这里都有…

ES5 数组方法forEach
ES6已经到了非学不可的地步了,对于ES5都不太熟的我决定是时候学习ES5了。 1. js 数组循环遍历。 数组循环变量,最先想到的就是 for(var i0;i<count;i)这样的方式了。 除此之外,也可以使用较简便的forEach 方式 2. forEach 函数。 使用如…

pytorch深度学习_了解如何使用PyTorch进行深度学习
pytorch深度学习PyTorch is an open source machine learning library for Python that facilitates building deep learning projects. Weve published a 10-hour course that will take you from being complete beginner in PyTorch to using it to code your own GANs (gen…

LwIP Application Developers Manual12---Configuring lwIP
1.前言 2.LwIP makefiles With minimal featuresC_SOURCES \ src/api/err.c \ src/core/init.c \ src/core/mem.c \ src/core/memp.c \ src/core/netif.c \ src/core/pbuf.c \ src/core/stats.c \ src/core/udp.c \ src/core/ipv4/icmp.c \ src/core/ipv4/inet.c \ src/core/i…

仿斗鱼聊天:基于CoreText的面向对象图文排版工具AWRichText
AWRichText 基于CoreText,面向对象,极简,易用,高效,支持精确点击,UIView混排,GIF动图,并不仅仅局限于图文混排的富文本排版神器。 代码地址:https://github.com/hardman/…

搭建nexus后,进入首页的时候出现warning: Could not connect to Nexus.错误
nexus出现这种问题,一般是版本太旧,换一个高版本的nexus就能解决了。 转载于:https://www.cnblogs.com/tietazhan/p/5459393.html

微软hackathon_武汉Hackathon的黑客之路–开发人员如何抗击COVID-19
微软hackathonThe Chinese New Year in 2020 was one of the saddest Chinese New Years in recent memory. After the sudden outbreak of the COVID-19 virus, the city pressed pause on all celebrations.2020年的农历新年是最近记忆中最可悲的农历新年之一。 在COVID-19病…

SVN版本控制系统使用
一.版本控制系统安装: 软件下载地址:https://www.visualsvn.com/downloads/ 二.安装版本控制系统以后,在window下,设置环境变量。 三.在命令提示符控制台查看服务器版本:svn --version 四.创建仓库:F:\DevR…

iOS的KVO实现剖析
KVO原理 对于KVO的原理,很多人都比较清楚了。大概是这样子的: 假定我们自己的类是Object和它的对象 obj, 当obj发送addObserverForKeypath:keypath消息后,系统会做3件事情: 动态创建一个Object的子类,名…

你真的以为了解java.io吗 呕心沥血 绝对干货 别把我移出首页了
文章结构1 flush的使用场景2 一个java字节流,inputstream 和 outputstream的简单例子3 分别测试了可能抛出java.io.FileNotFoundException,java.io.FileNotFoundException: test (拒绝访问。),java.io.FileNotFoundException: test.txt (系统…

GitHub为所有人免费提供了所有核心功能-这就是您应该关心的原因
Just a couple of days ago, GitHub wrote a blog article stating that it is now free for teams. Heres the official blog article if youre interested. 就在几天前,GitHub写了一篇博客文章,指出它现在对团队免费。 如果您有兴趣,这是官…

什么是ObjCTypes?
先看一下消息转发流程: 在forwardInvocation这一步,你必须要实现一个方法: - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector OBJC_SWIFT_UNAVAILABLE(""); 该方法用于说明消息的返回值和参数类型。NSMethodSignature是方法签名&#x…

0基础JavaScript入门教程(一)认识代码
1. 环境: JavaScript简称js,后续我们将使用js来代替JavaScript。 认识代码前,需要安装js代码运行环境。 安装nodejs:在https://nodejs.org/zh-cn/ 下载LTS版本,然后安装安装visual studio code:https://…

junit、hamcrest、eclemma的安装与使用
1、junit的安装与使用 1.1 安装步骤 1)从http://www.junit.org/ 下载junit相应的jar包; 2) 在CLASSPATH中加入JAR包所在的路径,如E:\Java\jar\junit\junit-4.10.jar; 3) 将junit-4.10.jar加入到项目的lib文…

如何撰写将赢得客户青睐的自由职业者提案和免费模板
Your prospective client asks you to provide them with a quote. So you just send them the quote, right?您的潜在客户要求您提供报价。 所以您只给他们发送报价吧? Wrong.错误。 If you did, you would be missing out on a massive opportunity here.如果这…

2. 把一幅图像进行平移。
实验二 #include "cv.h" #include<stdio.h> #include "highgui.h" IplImage *PingYi(IplImage *src, int h0, int w0); int main(int argc, char** argv) {IplImage* pImg; //声明IplImage指针IplImage* pImgAfterMove;pImg cvLoadImage("601…

后台的代理nginx部署方法
软件包如下:nginx-1.10.0.tar.gznginx-http-concat-master.zipngx_cache_purge-2.3.tar.gzopenssl-1.0.2h.tar.gzpcre-8.39.tar.gzzlib-1.2.8.tar.gz ngin部署方法:上面的安装包都存放在/apps/svr/soft目录下:cd /apps/svr/softtar -zxf nginx-1.10.0.ta…
iOS中你可能没有完全弄清楚的(一)synthesize
1. 什么是synthesize synthesize中文意思是合成,代码中我们经常这样用。 interface Test: NSObject property (nonatomic, unsafe_unretained) int i; endimplementation Test synthesize i; end 复制代码 使用synthesize的2个步骤: 首先你要有在类声…
framer x使用教程_如何使用Framer Motion将交互式动画和页面过渡添加到Next.js Web应用程序
framer x使用教程The web is vast and its full of static websites and apps. But just because those apps are static, it doesnt mean they have to be boring. 网络非常庞大,到处都是静态的网站和应用。 但是,仅仅因为这些应用程序是静态的…

POJ 2429
思路:a/n*b/nlcm/gcd 所以这道题就是分解ans.dfs枚举每种素数情况。套Miller_Rabin和pollard_rho模板 1 //#pragma comment(linker, "/STACK:167772160")//手动扩栈~~~~hdu 用c交2 #include<cstdio>3 #include<cstring>4 #include<cstdlib…

iOS中你可能没有完全弄清楚的(二)自己实现一个KVO源码及解析
前几天写了一篇blog(点这里),分析了系统KVO可能的实现方式。并添加了简单代码验证。 既然系统KVO不好用,我们完全可以根据之前的思路,再造一个可以在项目中使用的KVO的轮子。 代码已经上传到github: https://github.…

js中的preventDefault与stopPropagation详解
1. preventDefault: 比如<a href"http://www.baidu.com">百度</a>,这是html中最基础的东西,起的作用就是点击百度链接到http://www.baidu.com,这是属于<a>标签的默认行为;preventDefault方法就是可以阻止它的默认行为的发生而发生其他…

angular过滤字符_如何使用Angular和Azure计算机视觉创建光学字符读取器
angular过滤字符介绍 (Introduction) In this article, we will create an optical character recognition (OCR) application using Angular and the Azure Computer Vision Cognitive Service. 在本文中,我们将使用Angular和Azure计算机视觉认知服务创建一个光学字…

javascript函数全解
0.0 概述 本文总结了js中函数相关的大部分用法,对函数用法不是特别清晰的同学可以了解一下。 1.0 简介 同其他语言不同的是,js中的函数有2种含义。 普通函数:同其他语言的函数一样,是用于封装语句块,执行多行语句的…
MYSQL explain详解[转载]
explain显示了mysql如何使用索引来处理select语句以及连接表。可以帮助选择更好的索引和写出更优化的查询语句。 虽然这篇文章我写的很长,但看起来真的不会困啊,真的都是干货啊!!!! 先解析一条sql语句&…

CodeForces 157A Game Outcome
A. Game Outcometime limit per test2 secondsmemory limit per test256 megabytesinputstandard inputoutputstandard outputSherlock Holmes and Dr. Watson played some game on a checkered board n n in size. During the game they put numbers on the boards squares…

我使用Python和Django在自己的网站上建立了一个会员专区。 这是我学到的东西。
I decided it was time to upgrade my personal website in order to allow visitors to buy and access my courses through a new portal. 我认为是时候升级我的个人网站了,以允许访问者通过新的门户购买和访问我的课程 。 Specifically, I wanted a place for v…

详解AFNetworking的HTTPS模块
0.0 简述 文章内容包括: AFNetworking简介ATS和HTTPS介绍AF中的证书验证介绍如何创建服务端和客户端自签名证书如何创建简单的https服务器对CA正式证书和自签名证书的各种情况进行代码验证 文中所涉及的文件和脚本代码请看这里。 1.0 AFNetworking简介 AFNetwo…

字符串专题:map POJ 1002
第一次用到是在‘校内赛总结’扫地那道题里面,大同小异 map<string,int>str 可以专用做做字符串的匹配之类的处理 string donser; str [donser] 自动存donser到map并且值加一,如果发现重复元素不新建直接加一, map第一个参数是key&…