1、数据类型
- 简单类型
1、整数 2;浮点数2.1;字符串 "abc";空None;布尔值True/False,注意大小写!
2、布尔值可以用 and/or/not 进行运算,相当于 JS 的 &&/||/!
- 复杂类型
1、数组 list=['a','b'];元祖 tuple=('a','b');对象 dict={'Michael': 95, 'Bob': 75, 'Tracy': 85};集合set=set([1, 2, 3])
2、list基本操作
// 新建
array = [1,2,3]
range_list = list(range(100)) // 0-99 的 list
// 取值
array[0]
array[-1] // 取最后一个
// 长度
len(array)
// 增加
array.append(4)
// 删除指定位置元素
array.pop(i) // 不传值则删除末尾
// 指定位置插入
array.insert(4,5) // 索引为4的位置插入5
// 切片操作
L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
L[0:3] // 取前三个
L[:5:2] // 前5个数,每隔2取一个
// 列表生成式
[x * x for x in range(1, 11) if x % 2 == 0] // [4, 16, 36, 64, 100]
3、tuple 与 list 相似,唯一不同就是 tuple 一经赋值就不允许再改变,其元素都是 readonly。注意tuple有个小陷阱:
t = (1) // 等价于 t=1
t=(1,) // 这才是一个元素的tuple
4、dict 基本操作
dict2={'Michael': 95, 'Bob': 75, 'Tracy': 85} // 创建
dict2.get('Bob',-1) // 75 ,取值,若属性不存在,则取默认值-1
dict2.pop('Bob') // 删除
// 遍历
d = {'a': 1, 'b': 2, 'c': 3}
for key,value in d.items():
print(key,value)
{ k: v for k, v in vars(namespace).items() if v } // 字典生成器
5、set 基本操作
set 里的元素不会重复
s = set([1, 2, 3])
s.add(4)
s.remove(4)
2、常用语法
- 变量
Python 中变量声明不要用用关键字,直接写变量名称即可
a=1
b=1.2
c='test'
d=True and False
e=None
classmates = ['Michael', 'Bob', 'Tracy']
- 函数
// 定义
def my_abs(x):
if x >= 0:
return x
else:
return -x
// 调用
my_abs(3)
1、函数体内可用 pass 表示什么也不做,仅仅作为占位符;return 用于返回
2、函数参数-位置参数
// x,n 都是位置参数
def power(x, n):
s = 1
while n > 0:
n = n - 1
s = s * x
return s
3、函数参数-默认参数
def power(x, n=2):
s = 1
while n > 0:
n = n - 1
s = s * x
return s
4、函数参数-可变参数,类似JS的剩余参数
def calc(*numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum
// 调用
calc(1,2,3,4)
5、函数参数-关键字参数
def person(name, age, **kw):
print('name:', name, 'age:', age, 'other:', kw)
person('Bob', 35, city='Beijing') // name: Bob age: 35 other: {'city': 'Beijing'}
person('Adam', 45, gender='M', job='Engineer') // name: Adam age: 45 other: {'gender': 'M', 'job': 'Engineer'}
- 流程控制
if age >= 6:
print('teenager')
elif age >= 18:
print('adult')
else:
print('kid')
- 循环
// while 循环
sum = 0
n = 99
while n > 0:
sum = sum + n
n = n - 2
print(sum)
// for in 循环
sum = 0
for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
sum = sum + x
print(sum)
- 类
class Student(object): // 继承 object
name2 = 'Student' // 类属性,可被实例访问,不要与共有属性同名,否则会先访问共有属性,共有属性不存在时才访问类属性
def __init__(self, name, score,class='302'): // 构造函数
self.name = name // 共有属性,可被实例修改与访问
self.score = score
self.__class = class // 私有属性,实例不可访问和修改
def print_score(self): // 实例函数
print('%s: %s' % (self.name, self.score))
def get_grade(self):
if self.score >= 90:
return 'A'
elif self.score >= 60:
return 'B'
else:
return 'C'
// 创造实例
student = Student('FYC',100)
- 类型判断
总是优先使用isinstance()判断类型,可以将指定类型及其子类“一网打尽”。
// 基本类型都可以用type()判断
type(123) //
type(123)==int // True
type('str') //
type(None) //
type(abs) //
type(abs)==types.BuiltinFunctionType
type(a) //
// 要判断class的类型,可以使用isinstance()函数
isinstance('a', str) // True
isinstance(a,Animal) // True
isinstance([1, 2, 3], (list, tuple)) // True,表示是否是 list/tuple 类型之一
可以使用 dir(变量) 查看变量对应的对象所有可用的方法
dir('ABC') // ['__add__', '__class__',..., '__subclasshook__', 'capitalize', 'casefold',..., 'zfill']
- 异常捕获
// 抛出错误
def foo(s):
n = int(s)
if n==0:
raise ValueError('invalid value: %s' % s)
return 10 / n
// 捕获错误
def main():
try:
bar('0')
except Exception as e:
print('Error:', e)
finally:
print('finally...')
- 模块导入/导出
// 导入全部
import sys
// 导入部分
from datetime import datetime // 从 datetime 模块导入 datetime 方法
// 导出
__all__ = ['sys', '_static', 'test_func']
默认情况下,一个模块内的所有不以_开头的属性都被导出了;如果在模块文件中顶层的任何位置,增加定义一个特殊列表__all__ = ['sys', '_static', 'test_func'],则只有 __all__ 里的属性会被导出
3、常用内置模块及三方模块
- sys
系统参数、输入输出等相关
sys.argv // 一个list,获取命名行运行时的参数,第一个元素是脚本名称
sys.version // python 版本
sys.exit() // 退出python解释器
sys.stdout.flush() // 清空标准输出数据
- os.path
文件操作相关
path.join(path1,path2)
path.exists(path)
path.isfile(path)
path.isdir(path)
- zipfile
创建zip文件
zip_ref = zipfile.ZipFile(file, 'r')
zip_ref.extractall(folder_name) // 从归档中提取出所有成员放入当前工作目录
zip_ref.close()
- argparse
命令行解析,类似JS的 commander.js
parser = argparse.ArgumentParser(description='xx CI Build Tool')
parser.add_argument('-b', '--build-number',
help='build number', default='')
parser.add_argument('-p', '--platform',
help='platform', default='mac')
args = parser.parse_args()
build_number = args.build_number
platform = args.platform
- pathlib
更高级别的 path 处理
from pathlib import Path
p = Path('.') // p就拥有了当前目录的很多信息
[x for x in p.iterdir() if x.is_dir()]
- re
正则表达式
prog = re.compile(pattern)
result = prog.match(string)
- yaml
yaml 文件与python 字典互相转译工具,需额外安装 pip install yaml
import yaml
f = open(r'E:\AutomaticTest\Test_Framework\config\config.yml')
y = yaml.load(f)
print (y)
- pystache
python版Mustache,需额外安装 pip install pystache
import pystache
print pystache.render('Hi {{person}}!', {'person': 'Mom'}) // Hi Mom
- request
更加方便的发送请求,需额外安装 pip install request
import request
requests.get('https://www.douban.com/', headers={'User-Agent': 'Mozilla/5.0
(iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit'},params={"test",1},cookies={"test":2})
upload_files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=upload_files) // 上传文件
- getopt
命令行处理
# 语法
getopt.getopt(args, shortopts, longopts=[])
# args指的是当前脚本接收的参数,它是一个列表,可以通过sys.argv获得
# shortopts 是短参数 啥是短参数啊? 类似于 这样:python test.py -h # 输出帮助信息
# longopts 是长参数 啥是长参数啊? 类似于 这样:python test.py -# help # 输出帮助信息
# 用法
opts,args = getopt.getopt(sys.argv[1:],'-h-f:-v',['help','filename=','version'])
for opt_name,opt_value in opts:
if opt_name in ('-h','--help'):
print("[*] Help info")
exit()
if opt_name in ('-v','--version'):
print("[*] Version is 0.01 ")
exit()
if opt_name in ('-f','--filename'):
fileName = opt_value
print("[*] Filename is ",fileName)
# do something
exit()
# 调用
python3.5 test.py --filename=test # 输出:[*] Filename is test
定义了'-h-f:-v' ,在-f后面多了一个":"。这个":"代表了当前参数是有值的,是一个参数名+参数值的参数,将会保存到opts变量中。长参数名的方式和短参数差不多,唯一的区别就是长参数如果要接收值,那必须得在后面加上一个"="