版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、 Python 语法实战指南目 录 TOC o 1-3 h z u HYPERLINK l _Toc530830033 1.基础语法 PAGEREF _Toc530830033 h 3 HYPERLINK l _Toc530830034 2.表达式与控制流 PAGEREF _Toc530830034 h 9 HYPERLINK l _Toc530830035 3.基本数据类型 PAGEREF _Toc530830035 h 11 HYPERLINK l _Toc530830036 4.集合类型 PAGEREF _Toc530830036 h 17 HYPERLINK l _Toc5308300
2、37 5.函数 PAGEREF _Toc530830037 h 25 HYPERLINK l _Toc530830038 6.类与对象 PAGEREF _Toc530830038 h 31 HYPERLINK l _Toc530830039 7.异常与测试 PAGEREF _Toc530830039 h 37 HYPERLINK l _Toc530830040 8.存储 PAGEREF _Toc530830040 h 39 HYPERLINK l _Toc530830041 9.网络交互 PAGEREF _Toc530830041 h 45 HYPERLINK l _Toc530830042
3、10.数据存储 PAGEREF _Toc530830042 h 47基础语法Python 是一门高阶、动态类型的多范式编程语言;定义 Python 文件的时候我们往往会先声明文件编码方式:# 指定脚本调用方式#!/usr/bin/env python# 配置 utf-8 编码# -*- coding: utf-8 -*-# 配置其他编码# -*- coding: -*-# Vim 中还可以使用如下方式# vim:fileencoding=人生苦短,请用 Python,大量功能强大的语法糖的同时让很多时候 Python 代码看上去有点像伪代码。譬如我们用 Python 实现的简易的快排相较于 J
4、ava 会显得很短小精悍:def quicksort(arr): if len(arr) = 1: return arr pivot = arrlen(arr) / 2 left = x for x in arr if x pivot return quicksort(left) + middle + quicksort(right)print quicksort(3,6,8,10,1,2,1)# Prints 1, 1, 2, 3, 6, 8, 10控制台交互可以根据_name_关键字来判断是否是直接使用 python 命令执行某个脚本,还是外部引用;Google 开源的 fire 也是不错
5、的快速将某个类封装为命令行工具的框架:import fireclass Calculator(object): A simple calculator class. def double(self, number): return 2 * numberif _name_ = _main_: fire.Fire(Calculator)# python calculator.py double 10 # 20# python calculator.py double -number=15 # 30Python 2 中 print 是表达式,而 Python 3 中 print 是函数;如果希望在
6、Python 2 中将 print 以函数方式使用,则需要自定义引入:from _future_ import print_function我们也可以使用 pprint 来美化控制台输出内容:import pprintstuff = spam, eggs, lumberjack, knights, nipprint.pprint(stuff)# 自定义参数pp = pprint.PrettyPrinter(depth=6)tup = (spam, (eggs, (lumberjack, (knights, (ni, (dead,(parrot, (fresh fruit,)pp.pprint(
7、tup)模块Python 中的模块(Module)即是 Python 源码文件,其可以导出类、函数与全局变量;当我们从某个模块导入变量时,函数名往往就是命名空间(Namespace)。而 Python 中的包(Package)则是模块的文件夹,往往由_init_.py指明某个文件夹为包:# 文件目录someDir/ main.py siblingModule.py# siblingModule.pydef siblingModuleFun(): print(Hello from siblingModuleFun)def siblingModuleFunTwo(): print(Hello fr
8、om siblingModuleFunTwo)import siblingModuleimport siblingModule as sibModsibMod.siblingModuleFun()from siblingModule import siblingModuleFunsiblingModuleFun()try: # Import someModuleA that is only available in Windows import someModuleAexcept ImportError: try: # Import someModuleB that is only avail
9、able in Linux import someModuleB except ImportError:Package 可以为某个目录下所有的文件设置统一入口:someDir/ main.py subModules/ _init_.py subA.py subSubModules/ _init_.py subSubA.py# subA.pydef subAFun(): print(Hello from subAFun)def subAFunTwo(): print(Hello from subAFunTwo)# subSubA.pydef subSubAFun(): print(Hello f
10、rom subSubAFun)def subSubAFunTwo(): print(Hello from subSubAFunTwo)# _init_.py from subDir# Adds subAFun() and subAFunTwo() to the subDir namespace from .subA import *# The following two import statement do the same thing, they add subSubAFun() and subSubAFunTwo() to the subDir namespace. The first
11、one assumes _init_.py is empty in subSubDir, and the second one, assumes _init_.py in subSubDir contains from .subSubA import *.# Assumes _init_.py is empty in subSubDir# Adds subSubAFun() and subSubAFunTwo() to the subDir namespacefrom .subSubDir.subSubA import *# Assumes _init_.py in subSubDir has
12、 from .subSubA import *# Adds subSubAFun() and subSubAFunTwo() to the subDir namespacefrom .subSubDir import *# _init_.py from subSubDir# Adds subSubAFun() and subSubAFunTwo() to the subSubDir namespacefrom .subSubA import *# main.pyimport subDirsubDir.subAFun() # Hello from subAFunsubDir.subAFunTwo
13、() # Hello from subAFunTwosubDir.subSubAFun() # Hello from subSubAFunsubDir.subSubAFunTwo() # Hello from subSubAFunTwo表达式与控制流条件选择Python 中使用 if、elif、else 来进行基础的条件选择操作:if x 0: x = 0 print(Negative changed to zero) elif x = 0: print(Zero) else: print(More)Python 同样支持 ternary conditional operator:a if c
14、ondition else b也可以使用 Tuple 来实现类似的效果:# test 需要返回 True 或者 False(falseValue, trueValue)test# 更安全的做法是进行强制判断(falseValue, trueValue)test = True# 或者使用 bool 类型转换函数(falseValue, trueValue)bool()循环遍历for-in 可以用来遍历数组与字典:words = cat, window, defenestratefor w in words: print(w, len(w)# 使用数组访问操作符,能够迅速地生成数组的副本for w
15、 in words: if len(w) 6: words.insert(0, w)# words - defenestrate, cat, window, defenestrate如果我们希望使用数字序列进行遍历,可以使用 Python 内置的range函数:a = Mary, had, a, little, lambfor i in range(len(a): print(i, ai)基本数据类型可以使用内建函数进行强制类型转换(Casting):int(str)float(str)str(int)str(float)Number: 数值类型x = 3print type(x) # Pri
16、nts print x # Prints 3print x + 1 # Addition; prints 4print x - 1 # Subtraction; prints 2print x * 2 # Multiplication; prints 6print x * 2 # Exponentiation; prints 9x += 1print x # Prints 4x *= 2print x # Prints 8y = 2.5print type(y) # Prints print y, y + 1, y * 2, y * 2 # Prints 2.5 3.5 5.0 6.25布尔类
17、型Python 提供了常见的逻辑操作符,不过需要注意的是 Python 中并没有使用 &、| 等,而是直接使用了英文单词。t = Truef = Falseprint type(t) # Prints print t and f # Logical AND; prints Falseprint t or f # Logical OR; prints Trueprint not t # Logical NOT; prints Falseprint t != f # Logical XOR; prints TrueString: 字符串Python 2 中支持 Ascii 码的 str() 类型,
18、独立的 unicode() 类型,没有 byte 类型;而 Python 3 中默认的字符串为 utf-8 类型,并且包含了 byte 与 bytearray 两个字节类型:type(Guido) # string type is str in python2# # 使用 _future_ 中提供的模块来降级使用 Unicodefrom _future_ import unicode_literalstype(Guido) # string type become unicode# Python 字符串支持分片、模板字符串等常见操作:var1 = Hello World!var2 = Pyth
19、on Programmingprint var10: , var10print var21:5: , var21:5# var10: H# var21:5: ythoprint My name is %s and weight is %d kg! % (Zara, 21)# My name is Zara and weight is 21 kg!str0:4len(str)string.replace(-, ),.join(list)hi 0.format(j)str.find(,)str.index(,) # same, but raises IndexErrorstr.count(,)st
20、r.split(,)str.lower()str.upper()str.title()str.lstrip()str.rstrip()str.strip()str.islower()# 移除所有的特殊字符re.sub(A-Za-z0-9+, , mystring)如果需要判断是否包含某个子字符串,或者搜索某个字符串的下标:# in 操作符可以判断字符串if blah not in somestring: continue# find 可以搜索下标s = This be a stringif s.find(is) = -1: print No is here!else: print Found
21、is in the string.Regex: 正则表达式import re# 判断是否匹配re.match(raeiou, str)# 以第二个参数指定的字符替换原字符串中内容re.sub(raeiou, ?, str)re.sub(r(xyz), r1, str)# 编译生成独立的正则表达式对象expr = pile(r.$)expr.match(.)expr.sub(.)下面列举了常见的表达式使用场景:# 检测是否为 HTML 标签re.search(*, )# 常见的用户名密码re.match(a-zA-Z0-9-_3,16$, Foo) is not Nonere.match(w|-
22、_3,16$, Foo) is not None# Emailre.match(a-z0-9_.-+)(da-z.-+).(a-z.2,6)$, hello.world)# Urlexp = pile(r(https?:/)? # match http or https (da-z.-+) # match domain .(a-z.2,6) # match domain (/w .-*)/?$ # match api or file , re.X)exp.match()# IP 地址exp = pile(r(?:(?:250-5 |20-40-9 |1?0-90-9?).)3 (?:250-5
23、 |20-40-9 |1?0-90-9?)$, re.X)exp.match()集合类型List: 列表Operation: 创建增删list 是基础的序列类型:l = l = list()# 使用字符串的 split 方法,可以将字符串转化为列表str.split(.)# 如果需要将数组拼装为字符串,则可以使用 join list1 = 1, 2, 3str1 = .join(list1)# 如果是数值数组,则需要先进行转换list1 = 1, 2, 3str1 = .join(str(e) for e in list1)可以使用 append 与 extend 向数组中插入元素或者进行数组
24、连接x = 1, 2, 3x.append(4, 5) # 1, 2, 3, 4, 5x.extend(4, 5) # 1, 2, 3, 4, 5,注意 extend 返回值为 None可以使用 pop、slices、del、remove 等移除列表中元素:myList = 10,20,30,40,50# 弹出第二个元素myList.pop(1) # 20# myList: myList.pop(1)# 如果不加任何参数,则默认弹出最后一个元素myList.pop()# 使用 slices 来删除某个元素a = 1, 2, 3, 4, 5, 6 index = 3 # Only Positiv
25、e indexa = a:index + aindex+1 :# 根据下标删除元素myList = 10,20,30,40,50rmovIndxNo = 3del myListrmovIndxNo # myList: 10, 20, 30, 50# 使用 remove 方法,直接根据元素删除letters = a, b, c, d, enumbers.remove(numbers1)print(*letters) # used a * to make it unpack you dont have toIteration: 索引遍历你可以使用基本的 for 循环来遍历数组中的元素,就像下面介个
26、样纸:animals = cat, dog, monkeyfor animal in animals: print animal# Prints cat, dog, monkey, each on its own line.如果你在循环的同时也希望能够获取到当前元素下标,可以使用 enumerate 函数:animals = cat, dog, monkeyfor idx, animal in enumerate(animals): print #%d: %s % (idx + 1, animal)# Prints #1: cat, #2: dog, #3: monkey, each on i
27、ts own linePython 也支持切片(Slices):nums = range(5) # range is a built-in function that creates a list of integersprint nums # Prints 0, 1, 2, 3, 4print nums2:4 # Get a slice from index 2 to 4 (exclusive); prints 2, 3print nums2: # Get a slice from index 2 to the end; prints 2, 3, 4print nums:2 # Get a
28、slice from the start to index 2 (exclusive); prints 0, 1print nums: # Get a slice of the whole list; prints 0, 1, 2, 3, 4print nums:-1 # Slice indices can be negative; prints 0, 1, 2, 3nums2:4 = 8, 9 # Assign a new sublist to a sliceprint nums # Prints 0, 1, 8, 9, 4Comprehensions: 变换Python 中同样可以使用 m
29、ap、reduce、filter,map 用于变换数组:# 使用 map 对数组中的每个元素计算平方items = 1, 2, 3, 4, 5squared = list(map(lambda x: x*2, items)# map 支持函数以数组方式连接使用def multiply(x): return (x*x)def add(x): return (x+x)funcs = multiply, addfor i in range(5): value = list(map(lambda x: x(i), funcs) print(value)reduce 用于进行归纳计算:# reduce
30、将数组中的值进行归纳from functools import reduceproduct = reduce(lambda x, y: x * y), 1, 2, 3, 4)# Output: 24filter 则可以对数组进行过滤:number_list = range(-5, 5)less_than_zero = list(filter(lambda x: x 0: return positive elif x 0: return negative else: return zerofor x in -1, 0, 1: print sign(x)# Prints negative, zer
31、o, positivePython 支持运行时创建动态函数,也即是所谓的 lambda 函数:def f(x): return x*2# 等价于g = lambda x: x*2参数Option Arguments: 不定参数def example(a, b=None, *args, *kwargs): print a, b print args print kwargsexample(1, var, 2, 3, word=hello)# 1 var# (2, 3)# word: helloa_tuple = (1, 2, 3, 4, 5)a_dict = 1:1, 2:2, 3:3examp
32、le(1, var, *a_tuple, *a_dict)# 1 var# (1, 2, 3, 4, 5)# 1: 1, 2: 2, 3: 3生成器def simple_generator_function(): yield 1 yield 2 yield 3for value in simple_generator_function(): print(value)# 输出结果# 1# 2# 3our_generator = simple_generator_function()next(our_generator)# 1next(our_generator)# 2next(our_gener
33、ator)#3# 生成器典型的使用场景譬如无限数组的迭代def get_primes(number): while True: if is_prime(number): yield number number += 1装饰器装饰器是非常有用的设计模式:# 简单装饰器from functools import wrapsdef decorator(func): wraps(func) def wrapper(*args, *kwargs): print(wrap function) return func(*args, *kwargs) return wrapperdecoratordef ex
34、ample(*a, *kw): passexample._name_ # attr of function preserve# example# Decorator # 带输入值的装饰器from functools import wrapsdef decorator_with_argument(val): def decorator(func): wraps(func) def wrapper(*args, *kwargs): print Val is 0.format(val) return func(*args, *kwargs) return wrapper return decorat
35、ordecorator_with_argument(10)def example(): print This is example function.example()# Val is 10# This is example function.# 等价于def example(): print This is example function.example = decorator_with_argument(10)(example)example()# Val is 10# This is example function.类与对象类定义Python 中对于类的定义也很直接:class Gr
36、eeter(object): # Constructor def _init_(self, name): = name # Create an instance variable # Instance method def greet(self, loud=False): if loud: print HELLO, %s! % .upper() else: print Hello, %s % g = Greeter(Fred) # Construct an instance of the Greeter classg.greet() # Call an instance method; pri
37、nts Hello, Fredg.greet(loud=True) # Call an instance method; prints HELLO, FRED!# isinstance 方法用于判断某个对象是否源自某个类ex = 10isinstance(ex,int)Managed Attributes: 受控属性# property、setter、deleter 可以用于复写点方法class Example(object): def _init_(self, value): self._val = value property def val(self): return self._val
38、 val.setter def val(self, value): if not isintance(value, int): raise TypeError(Expected int) self._val = value val.deleter def val(self): del self._val property def square3(self): return 2*3ex = Example(123)ex.val = str# Traceback (most recent call last):# File , line 1, in# File test.py, line 12,
39、in val# raise TypeError(Expected int)# TypeError: Expected int类方法与静态方法class example(object): classmethod def clsmethod(cls): print I am classmethod staticmethod def stmethod(): print I am staticmethod def instmethod(self): print I am instancemethodex = example()ex.clsmethod()# I am classmethodex.stm
40、ethod()# I am staticmethodex.instmethod()# I am instancemethodexample.clsmethod()# I am classmethodexample.stmethod()# I am staticmethodexample.instmethod()# Traceback (most recent call last):# File , line 1, in# TypeError: unbound method instmethod() .对象实例化属性操作Python 中对象的属性不同于字典键,可以使用点运算符取值,直接使用 in
41、 判断会存在问题:class A(object): property def prop(self): return 3a = A()print prop in a._dict_ =, prop in a._dict_print hasattr(a, prop) =, hasattr(a, prop)print p =, p# prop in a._dict_ = False# hasattr(a, prop) = True# p = 3建议使用 hasattr、getattr、setattr 这种方式对于对象属性进行操作:class Example(object): def _init_(se
42、lf): = ex def printex(self): print This is an example# Check object has attributes# hasattr(obj, attr)ex = Example()hasattr(ex,name)# Truehasattr(ex,printex)# Truehasattr(ex,print)# False# Get object attribute# getattr(obj, attr)getattr(ex,name)# ex# Set object attribute# setattr(obj, attr, value)se
43、tattr(ex,name,example)# example异常与测试异常处理Context Manager - withwith 常用于打开或者关闭某些资源:host = localhostport = 5566with Socket(host, port) as s: while True: conn, addr = s.accept() msg = conn.recv(1024) print msg conn.send(msg) conn.close()单元测试from _future_ import print_functionimport unittestdef fib(n): r
44、eturn 1 if n=2 else fib(n-1)+fib(n-2)def setUpModule(): print(setup module)def tearDownModule(): print(teardown module)class TestFib(unittest.TestCase): def setUp(self): print(setUp) self.n = 10 def tearDown(self): print(tearDown) del self.n classmethod def setUpClass(cls): print(setUpClass) classme
45、thod def tearDownClass(cls): print(tearDownClass) def test_fib_assert_equal(self): self.assertEqual(fib(self.n), 55) def test_fib_assert_true(self): self.assertTrue(fib(self.n) = 55)if _name_ = _main_: unittest.main()存储文件读写路径处理Python 内置的_file_关键字会指向当前文件的相对路径,可以根据它来构造绝对路径,或者索引其他文件:# 获取当前文件的相对目录dir =
46、os.path.dirname(_file_) # srcapp# once youre at the directory level you want, with the desired directory as the final path node:dirname1 = os.path.basename(dir) dirname2 = os.path.split(dir)1 # if you look at the documentation, this is exactly what os.path.basename does.# 获取当前代码文件的绝对路径,abspath 会自动根据
47、相对路径与当前工作空间进行路径补全os.path.abspath(os.path.dirname(_file_) # D:WorkSpaceOWStoolui-tool-svnpythonsrcapp# 获取当前文件的真实路径os.path.dirname(os.path.realpath(_file_) # D:WorkSpaceOWStoolui-tool-svnpythonsrcapp# 获取当前执行路径os.getcwd()可以使用 listdir、walk、glob 模块来进行文件枚举与检索:# 仅列举所有的文件from os import listdirfrom os.path i
48、mport isfile, joinonlyfiles = f for f in listdir(mypath) if isfile(join(mypath, f)# 使用 walk 递归搜索from os import walkf = for (dirpath, dirnames, filenames) in walk(mypath): f.extend(filenames) break# 使用 glob 进行复杂模式匹配import globprint(glob.glob(/home/adam/*.txt)# /home/adam/file1.txt, /home/adam/file2.t
49、xt, 简单文件读写# 可以根据文件是否存在选择写入模式mode = a if os.path.exists(writepath) else w# 使用 with 方法能够自动处理异常with open(file.dat,mode) as f: f.write(.) . # 操作完毕之后记得关闭文件 f.close()# 读取文件内容message = f.read()复杂格式文件JSONimport json# Writing JSON datawith open(data.json, w) as f: json.dump(data, f)# Reading data backwith op
50、en(data.json, r) as f: data = json.load(f)XML我们可以使用lxml来解析与处理 XML 文件,本部分即对其常用操作进行介绍。lxml 支持从字符串或者文件中创建 Element 对象:from lxml import etree# 可以从字符串开始构造xml = root = etree.fromstring(xml)etree.tostring(root)# b# 也可以从某个文件开始构造tree = etree.parse(doc/test.xml)# 或者指定某个 baseURLroot = etree.fromstring(xml, base
51、_url=http:/where.it/is/from.xml)其提供了迭代器以对所有元素进行遍历:# 遍历所有的节点for tag in tree.iter(): if not len(tag): print tag.keys() # 获取所有自定义属性 print (tag.tag, tag.text) # text 即文本子元素值# 获取 XPathfor e in root.iter(): print tree.getpath(e)lxml 支持以 XPath 查找元素,不过需要注意的是,XPath 查找的结果是数组,并且在包含命名空间的情况下,需要指定命名空间:root.xpath(/page/text/text(),ns=prefix:url)# 可以使用 getpare
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2026年阿克苏市广播电视台(融媒体中心)人员招聘考试备考试题及答案详解
- 2026北京大学新结构经济学研究院招聘国内发展合作部研究员2人考试备考题库及答案解析
- 2026年阿克苏市国家电网系统事业单位人员招聘考试备考试题及答案详解
- 2026年不锈钢型材行业分析报告及未来发展趋势报告
- 2026年拆信刀行业分析报告及未来发展趋势报告
- 2026浙江舟山市普陀区交通运输局招聘编外人员1人笔试备考试题及答案解析
- 2026年机制水泥管行业分析报告及未来发展趋势报告
- 2026年聚硅氧烷消泡剂行业分析报告及未来发展趋势报告
- 2026年安庆市大观区卫生健康系统人员招聘笔试备考试题及答案解析
- 2026年电子飞行包行业分析报告及未来发展趋势报告
- 2026重庆联合产权交易所集团股份有限公司招聘13人考试备考试题及答案解析
- 2026中国文创产品市场消费趋势与商业模式创新研究报告
- 2026中考语文试题分类汇编《作文》练习题
- 2026年辽宁省二级建造师继续教育复习真题AB卷附答案详解
- 2025年冀人版三年级科学下册全套测试卷新版
- 药物医疗器械临床试验质量管理规范试题及答案
- YC/T 88.2-2006烟草机械喂料机第2部分:技术条件
- GB/T 10855-2016齿形链和链轮
- GA 1334-2016管制刀具分类与安全要求
- 2023年广州铁路职业技术学院单招职业适应性测试笔试模拟试题及答案解析
- DB44 2208-2019农村生活污水处理排放标准-(高清现行)
评论
0/150
提交评论