1
2
|
#coding=utf-8
#-*- coding:utf8 -*-
|
使用type返回实例所属的类型
1
2
3
4
5
6
|
>>>type(123)
int
>>>type(1.2)
float
>>>type(“hello”)
str
|
每个对象都有唯一的id
使用id()查看
判断实例是否属于特定类型
>>>isinstance(1,int) # Ture
1
2
|
>>> type(int)
<class 'type'>
|
赋值
1
2
3
4
5
6
|
>>> x=100
>>> x
100
>>> x += 2
>>> x
102
|
'False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'
1
2
3
4
5
6
|
False
""
None
0
[]
{}
|
1
2
3
4
5
6
7
8
9
|
#!/usr/bin/python3
counter = 100 # 整型变量
miles = 1000.0 # 浮点型变量
name = "胖猫" # 字符串
print (counter)
print (miles)
print (name)
|
多变量赋值
1
2
|
a = b = c = 1
a, b, c = 1, 2, "helloworld"
|
Python3 中有六个标准的数据类型:
- Number(数字)
- String(字符串)
- List(列表)
- Tuple(元组)
- Set(集合)
- Dictionary(字典)
Python3 的六个标准数据类型中:
- 不可变数据(3 个):Number(数字)、String(字符串)、Tuple(元组);
- 可变数据(3 个):List(列表)、Dictionary(字典)、Set(集合)。
进制
1
2
3
4
5
6
7
8
9
|
0b110011 # bin 51
0o12 #oct 10
0x64 #hex 100
bin(100) #'0b1100100'
#同理 oct(100) hex(100) int()还原
#也可以指定
int("0b1100100",2)
|
1
2
3
4
5
6
7
8
9
10
11
|
#python3
>>>4/2
2.0
>>>3//2
1
>>> 1.0//2.0
0.0
>>> -5/2
-2.5
>>> -5//2
-3
|
深拷贝浅拷贝
1
2
3
4
5
|
import copy
x2 = copy.copy(x) #浅
x3 = copy.deepcopy(x) #深
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
>>> 1/3
0.3333333333333333
#转换
>>> float(100)
100.0
>>> float("-100.123")
-100.123
>>> int(2.6),int(-2.6)# 截掉小数部分
(2, -2)
#使用math库对浮点数进行处理、
>>> from math import trunc,floor,ceil
>>> trunc(2.6), trunc(-2.6)#截掉小数部分
(2, -2)
>>> floor(2.6),floor(-2.6)#往数字小的方向取整数
(2, -3)
>>> ceil(2.6),ceil(-2.6)#往数字大的方向取整数
(3, -2)
|
1
2
3
4
5
6
7
|
>>> round(0.5)
0
>>> round(1.5)
2
#python对四舍五入操作存在不确定性 不同版本存在差异
>>> round(0.500001)
1
|
1
2
3
4
|
>>> x = [0,1,2,3,4,5,6]
>>> s = x[2:5]
>>> s
[2, 3, 4]
|
x[开始:结束:步长]
x[:5]省略开始
x[2:]省略结束
x[:]完整复制
x[::-1]反向步进 全部复制
x[5:2:-1] //5 4 3 反向
x[-2:-5:-1]// 负索引 5 4 3
x[-5:-2] //2 3 4
1
2
3
4
|
>>> x = [0,1,2,3,4,5,6]
>>> x[2:5] =[100,200] #相当于先删除 再插入
>>> x
[0, 1, 100, 200, 5, 6]
|
与其他语言if语句无太大差别,注意缩进就行了
1
2
3
4
5
6
|
if condition_1:
statement_block_1
elif condition_2:
statement_block_2
else:
statement_block_3
|
[输出表达式 + 数据迭代源 + 过滤表达式(可选)]
[x+10 for x in range(10) if x%2==0]
[10, 12, 14, 16, 18]
while 判断条件:
语句
while例子
1
2
3
4
5
6
7
8
9
10
11
|
#!/usr/bin/env python3
n = 100
sum = 0
counter = 1
while counter <= n:
sum = sum + counter
counter += 1
print("1 到 %d 之和为: %d" % (n,sum))
|
while。。。else。。。
1
2
3
4
5
6
7
8
|
#!/usr/bin/python3
count = 0
while count < 5:
print (count, " 小于 5")
count = count + 1
else:
print (count, " 大于或等于 5")
|
break语句会导致else语句不被执行,有break但是未被执行也算else
> < = !=
and or not
字符串存储Unicode文本
1
2
3
4
5
6
7
|
>>> s = "汉字"
>>> len(s) #python的len是真实个数
2
>>> hex(ord("汉"))
'0x6c49'
>>> chr(0x6c49)
'汉'
|
在 Python3.x 中 raw_input() 和 input() 进行了整合,去除了 raw_input( ),仅保留了input( )函数,其接收任意任性输入,将所有输入默认为字符串处理,并返回字符串类型。
Python3.x 中 input() 函数接受一个标准输入数据,返回为 string 类型。
1
2
3
4
5
6
7
8
|
>>> a = input()
123
>>> a
'123'
#如果需要整数123 则需要转换
>>> a = int(a)
>>> a
123
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
# .find()
# 查找到返回下标,查不到返回-1 ,rfind 从后面找
# .index()
# 查找不到程序错误
# .count()
# 查找次数
str.replace(str1,str2, start=0,end=len(mystr))
#遇到一个替换一个, 并不更改原串
#第三个参数 替换次数
str.split(" ")
# 字符串切割 变成列表
# split() 没有参数 默认按空格\t切
# .startswith()
# .endswith()
# 返回True
# .lower()
# .upper()
# 大写转为小写 小写转为大写
# .center(50) 居中
# ljust 靠左 rjust 靠右
# lstrip 左边空格删掉
# rstrip 右边的空格删掉
# strip 前后的空格都删掉
# .parttion("aa")
# 用aa字符串把整个字符串分成三个元组
# rparttion 从右边开始找
# splitlines
# 按行切割 删除空行
# isalpha
# isdigit
# isalnum() 既有数字又有字母
a = ["aaa","bbb","ccc"]
b = "="
b.join(a)
# "aaa=bbb=ccc"
|
1
2
3
4
5
6
7
8
9
10
11
12
|
# 第一个注释
# 第二个注释
'''
第三注释
第四注释
'''
"""
第五注释
第六注释
"""
|
序列都可以进行的操作包括索引,切片,加,乘,检查成员。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
#!/usr/bin/python3
# 列表的定义
list = [1, 2, 3.14 ,"老王" ]; #可以同时存储多种数据类型
list = [] # 就是列表
print ("list[0]: ", list[0])
print ("list[1:5]: ", list[1:5])
# 增
list.append()
list.insert(位置,添加的内容)
# list1+list2
list.extend(另一个列表) # 合并
## append和extend
# extend只能放可以迭代的,一个一个加进去
# append是把括号里当成一个整体 添加一个元素
# 删
list.pop() # 删除最后一个
list.remove("老王") # 按内容删,从左边删1个
del list[2] # 根据下标删 删除第三个元素
# 改
list[下标] = 新值
# 查
# in / not in
if "老赵" in names:
print("找到了")
|
| Python 表达式 |
结果 |
描述 |
| len([1, 2, 3]) |
3 |
长度 |
| [1, 2, 3] + [4, 5, 6] |
[1, 2, 3, 4, 5, 6] |
组合 |
| ['Hi!'] * 4 |
['Hi!', 'Hi!', 'Hi!', 'Hi!'] |
重复 |
| 3 in [1, 2, 3] |
True |
元素是否存在于列表中 |
| for x in [1, 2, 3]: print(x, end=" ") |
1 2 3 |
迭代 |
须是唯一的,但值则不必
可变类型不能当key(列表和字典)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
#!/usr/bin/python3
infor = {键:值,键:值}
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])
#修改
dict['Age'] = 8; # 更新 Age(key存在)
dict['tangyuan'] = "汤圆" # 添加信息(写一个新的key)
#查
dict['tangyuan'] #查找 key不存在报错
dict.get("tangyuan") # key不存在不报错
#删除
del dict['Name'] # 删除键 'Name'
dict.clear() # 清空字典
del dict # 删除字典
# 所有的键
infor.keys() # python2是列表 python3是对象
infor.values()
infor.items() # 列表 [两个元组] 每次循环都有key和value
|
注:元组只能读 不能修改
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
tup1 = ('Google', '汤圆', 1997, 2000)#定义元组
tup2 = (1, 2, 3, 4, 5, 6, 7 )
print ("tup1[0]: ", tup1[0])#访问元组
print ("tup2[1:5]: ", tup2[1:5])
a = (11,22)
b,c = a # b = 11 c = 22 (拆包)
tup1 = ();#创建空元组
#元组中只包含一个元素时,需要在元素后面添加逗号,否则括号会被当作运算符使用:
>>> tup1 = (50,)
>>> type(tup1) # 加上逗号,类型为元组
<class 'tuple'>
|
| Python 表达式 |
结果 |
描述 |
| len((1, 2, 3)) |
3 |
计算元素个数 |
| (1, 2, 3) + (4, 5, 6) |
(1, 2, 3, 4, 5, 6) |
连接 |
| ('Hi!',) * 4 |
('Hi!', 'Hi!', 'Hi!', 'Hi!') |
复制 |
| 3 in (1, 2, 3) |
True |
元素是否存在 |
| for x in (1, 2, 3): print (x,) |
1 2 3 |
迭代 |
存储非重复元素 ,
集合(set)是一个无序的不重复元素序列。
可以使用大括号 { } 或者 set() 函数创建集合,注意:创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典。
创建格式:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
>>>basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket) # 这里演示的是去重功能
{'orange', 'banana', 'pear', 'apple'}
>>> 'orange' in basket # 快速判断元素是否在集合内
True
>>> 'crabgrass' in basket
False
>>> # 下面展示两个集合间的运算.
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a
{'a', 'r', 'b', 'c', 'd'}
>>> a - b # 集合a中包含而集合b中不包含的元素
{'r', 'd', 'b'}
>>> a | b # 集合a或b中包含的所有元素
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b # 集合a和b中都包含了的元素
{'a', 'c'}
>>> a ^ b # 不同时包含于a和b的元素
{'r', 'd', 'b', 'm', 'z', 'l'}
|
for <variable> in <sequence>:
<statements>
else:
<statements>
1
2
3
4
5
6
7
|
languages = ["C", "C++", "Perl", "Python"]
for x in languages:
print (x)
#range
>>>for i in range(5):
... print(i)
|
1
2
3
4
5
6
7
|
nums = [11,22,33,44]
for tmp in nums:
print(tmp)
else:
print("===") # 循环正常结束打印一次(一定会执行)
#在for循环里break 不会进入else
|
1
2
3
4
5
6
|
#函数创建
def test(x, y=10):
x+=100
print(x,y)
test(1,2) #输出101 2
test(20) #输出 120 10
|
1
2
3
|
add = lambda x,y : x + y
print(add(1,2)) #3
|
1
2
3
4
5
|
def test(a,b,c=33,d=44,*args):#*args是位置参数收集
print(locals())
test(1,2,3,4,5,6,7,8)
#输出结果 {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'args': (5, 6, 7, 8)}
|
1
2
3
4
5
6
7
8
9
10
|
def test(n):
if n>0:
return 1,2,3 #返回多个数
elif n<0:
return -1,-2
return 0
print(test(1)) #(1, 2, 3)
print(test(-1)) #(-1, -2)
print(test(0)) #0
|
放在函数调用之前
1
2
3
4
5
|
wendu = 0
def fun():
global wendu # 声明修改全局变量
wendu = 33
|
1
2
3
4
5
6
7
8
9
10
|
# 对列表里的字典排序
infor.sort(key=lambda x:x['name'])
#参数传递
def test(a,b,func):
result = func(a,b)
return result
num = test(11,22,lambda x,y:x+y)
print(num)
|
python都是引用
如果是可变类型 直接修改,如果是不可变 ,指向一个新的
num += num #直接修改num的值
num = num + num #先得到一个临时的值,再重新指向
大象怎么关进冰箱
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
# fileRW.py
# 将一个列表中的字符串写入文件
f = open('test1.txt','w')
for x in ['aaa',123,'汤圆',True,'tangyuan']:
if type(x) == str:
f.write(x)
f.close()
#一次性读出到字符串
f = open('test1.txt','r')
xx = f.read()
print('xx=',xx)
f.close()
f.read(1) #读取一个字节
f.readline() # 返回值是字符串
f.readlines() # 返回值是列表 每一行是一个元素
#输出结果:xx= aaa汤圆tangyuan
|
| 模式 |
r |
r+ |
w |
w+ |
a |
a+ |
| 读 |
+ |
+ |
|
+ |
|
+ |
| 写 |
|
+ |
+ |
+ |
+ |
+ |
| 创建 |
|
|
+ |
+ |
+ |
+ |
| 覆盖 |
|
|
+ |
+ |
|
|
| 指针在开始 |
+ |
+ |
+ |
+ |
|
|
| 指针在结尾 |
|
|
|
|
+ |
+ |
| 模式 |
说明 |
| r |
以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。 |
| w |
打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。 |
| a |
打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。 |
| rb |
以二进制格式打开一个文件用于只读。文件指针将会放在文件的开头。这是默认模式。 |
| wb |
以二进制格式打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。 |
| ab |
以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。 |
| r+ |
打开一个文件用于读写。文件指针将会放在文件的开头。 |
| w+ |
打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。 |
| a+ |
打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。 |
| rb+ |
以二进制格式打开一个文件用于读写。文件指针将会放在文件的开头。 |
| wb+ |
以二进制格式打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。 |
| ab+ |
以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。如果该文件不存在,创建新文件用于读写。 |
.seek(2,0) # 从开头 向后偏移2个字节
1
2
3
4
5
6
7
8
9
10
|
f.seek(0,0) # 回到开头
f.tell()# 当前位置
# 第一个参数
微调 #python3不支持负数
# 第二个参数
0 文件开头
1 当前位置
3 文件末尾
|
os.rename
os.remove
os.mkdir
os.chdir #改变默认路径
os.getcwd
os.listdir("./") # 当前路径下所有文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
#手工迭代
>>> d = [0,1,2]
>>> x = d.__iter__()
>>> x.__next__()
0
>>> x.__next__()
1
>>> x.__next__()
2
>>> x.__next__()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
#自动迭代
for i in [0,1,2]:
print(i)#输出 0 1 2
|
图纸(类) 飞机(对象)
- 类的名称:类名
- 类的属性:一组数据
- 类的方法:允许操作的方法(行为)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
class A:
a = 100
def __init__(self,x): # 定义方法必须写上self
self.__x = x; #self相当于其他语言的this
def __str__(self): # 可以直接print
return "__x=%d" % __x
#私有方法
def __send_msg():
pass
def get_x(self):
return self.__x
class B(A):
b = "hello"
def __init__(self,x,y):
super().__init__(x)
self.y=y
def get_y(self):
return self.y
o = B(1,2)
print(o.get_x(),o.get_y())## 1 2
|
私有字段(Attribute)用双下划线开头__name
保护字段 protected _name 只循序本身和子类访问
1
2
3
4
5
6
7
8
9
|
class A(object) :pass
class B(A) :pass
class C(B) :pass
issubclass(A,object) #true
type(A) is A.__class__ #true
B.__base__ #A
A.__subclasses__() #[B]
|
__init__是可选的
1
2
3
4
5
6
7
8
9
|
class A(object):
def m(self):print("A.m")
def do(self):self.m()
class B(A):
def m(self):print("B.m")
A().do() #输出 A.m
B().do() #输出 B.m
|
- init : 构造函数,在生成对象时调用
- del : 析构函数,释放对象时使用
- str: 转文本 str(obj)
- repr : 打印,转换
- setitem : 按照索引赋值
- getitem: 按照索引获取值
- len: 获得长度
- cmp: 比较运算
- call: 函数调用
- add: 加运算
- sub: 减运算
- mul: 乘运算
- truediv: 除运算
- mod: 求余运算
- pow: 乘方
操作类 用类方法
操作实例 用实例方法
做一些和类数据没有关系的操作 用静态方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
class Game(object):
#类属性
num = 0
#实例方法
def __init__(self):
#实例属性
self.name = "laowang"
#类方法
@classmethod
def add_num(cls): # cls保存类的引用
cls.num=100 #类方法为了修改类属性
#静态方法
@staticmethod
def print_menu():
print("-------------")
#调用类方法
Game.add_num() #可以通过类名调用
game = Game()
game.add_num() #也可以通过对象调用
#调用静态方法
Game.print_menu() #ok
game.print_menu() #ok
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
class Dog(object):
def __init__(self):
pass
def __del__(self):
pass
def __new__(cls):
return object.__new__(cls) # 返回值是对象的一个引用
dog = Dog() # 1.调用__new__ 只负责创建对象
# 2.调用__init__ 只符合初始化
# 3.返回对象的引用
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
class Dog(object):
__instance = None
def __new__(cls):
if cls.__instance == None:
__instance = object.__new(cls)
return __instance
else:
return __instance
a = Dog()
print(id(a))
b = Dog()
print(id(b))
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
class Dog(object):
__instance = None
__init_flag = False #添加一个标志位
def __new__(cls,name):
if cls.__instance == None:
__instance = object.__new(cls)
return __instance
else:
return __instance
def __init__(self,name):
if Dog.__init_flag==False:
self.name=name
Dog.__init_flag = True #只初始化一次
a = Dog("旺财")
print(id(a))
b = Dog("哮天犬") # 虽然是单例,但是会init两次
print(id(b))
|
1
2
3
4
5
6
7
8
9
10
|
import sys
def test():
try:
raise Exception("err")
except: #python2的捕获所有异常,python3加个Exception
print(sys.exc_info())
raise # 重新抛出异常,触发默认异常处理
test()
#(<class 'Exception'>, Exception('err'), <traceback object at 0x0000026EB3FB70C8>)
|
异常处理
- try 需要保护的代码块
- except 异常发生时 按所属类型捕获
- else 未发生异常执行 前面需要至少有1个except
- finally 无论是否发生异常 总是执行
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
def test(n):
try:
print("try")
if not n:
raise Exception()
except (NameError,FileNotFoundError):
print("#python3捕获多个异常 加括号 是元组")
except Exception as e:
print("所有异常的总称")
print(e)
else:
print("没有异常才会执行")
finally:
print("不管是否产生异常 总会执行")
# 关文件
test(0)
#try
#except
#finally
test(1)
#try
#else
#finally
|
pip 管理python模块的工具
1
2
3
4
|
import sys #引入所有函数
from xxx import * #引入模块中所有函数
from xxx import xxx,xxx #引入xxx函数 没列入的不引入
import xxx as xxx #重命名
|
使用from example.module01 import * 调用函数不需要加包名 如myfun1(10,20)
使用from example import module01 调用函数需要加模块名和函数名,不需要加包名 如module01.myfun1(10,20)
创建一个__init__.py的空文件,这个文件夹就是包
导入包 这个文件就会执行
1
2
3
4
5
6
7
|
__all__ = ["send_msg"] # 影响from
#print("hahaha") #导入包会执行的
#import sendmsg # 导入包 python2用
from . import sendmsg
|
在包文件夹相同路径旁边 新建一个setup.py
1
2
3
|
from distutils.core import setup
setup(name="test", version="1.0", description="xuehu96's module", author="xuehu96", py_modules=['TestMsg.sendmsg', 'TestMsg.recvmsg'])
|
运行安装
1
2
3
4
5
6
7
|
#编译
python3 setup.py build
python3 setup.py sdisk
#安装
tar -zxvf 压缩包
python3 setup.py install #安装到系统里
|
1
2
3
4
5
|
import sys
print(sys.argv)
print("欢迎%s的到来"% sys.argv[0])
|
创建一个很大的列表
python2 range有风险
python3 什么时候要什么时候生成
1
2
3
4
5
|
a = [ i for i in range(1,18)] #1-17
b = [ 1111 for i in range(10)] #10个1111
c = [ i for i in range(10) if 1%2==0] #for和if
d = [ i for i in range (3) for j in range(2)] #6次 [0,0,1,1,2,2,]
e = [(i,j,k) for i in range(3) for j in range(2) for k in range(3) ] # [(000)(001)(002)(010)....(212)]
|