本文由博主与另一位博主合作创作:链接:Sookie#
单行:#
多行:’’'或者"""
False,class,finally,is,None,for,continue,try...
help()
,然后keywords
(退出help()
,用quit)dir(__builtins__)
_*
是特殊的标识符.在交互式执行中使用,表示之前的计算结果.__*__
通常是系统定义的函数名.<变量>=input([提示,字符串])
print(value1, value2, ..., sep=[str],end=[str])
你能够完成一定功能的程序段
单 词 → 语 句 → 函 数 → 模 块 → 包 → 库 单词\rightarrow 语句 \rightarrow 函数 \rightarrow 模块 \rightarrow 包\rightarrow 库 单词→语句→函数→模块→包→库
相关构成方式如上图.
使用模块的函数,需要引入import [A]
和使用[A].[B]
import math
math.sqrt(2)
引入一部分函数from [A] import [B],[C],...
,使用的时候[B],[C]
即可
pi,e
from math import *
print("e="+str(e),"pi="+str(pi),sep='\n',end='\n')
print("\n")
print("id(11)="+str(id(11)),"id('python')"+str(id('python')),sep='\n',end='\n')
print("type(11)="+str(type(11)),"type(1.1)="+str(type(1.1)),"type('python')="+str(type('python')),sep='\n',end='\n')
print("\n")
print("type(type(11))="+str(type(type(11))),end='\n')
print("type(id(11))="+str(type(id(11))),end='\n')
e=2.718281828459045
pi=3.141592653589793
id(11)=140719947748480
id('python')2211218698568
type(11)=
type(1.1)=
type('python')=
type(type(11))=
type(id(11))=
#需要注意的是,引用是一个指向的机制,减少内存的消耗.
a = 112
print(type(a))
print(id(a))
print(id(112))
b = 112
print(id(b))
#验证
print()
a = 211
print(type(a))
print(id(a))
print(id(211))
#验证2
print()
a = "ABS"
print(type(a))
print(id(a))
print(id("ABS"))
140719947751712
140719947751712
140719947751712
140719947754880
140719947754880
2211248712872
2211248712872
x,y,z = 5,7,8
print(x,y,z,sep=', ')
x = (1,2,'t')#元组的概念,不可修改
print(x)
5, 7, 8
(1, 2, 't')
a = 5
print(a.bit_length())
a = 254
print(a.bit_length())
b = 112
print(b.bit_length())
#print(112.bit_length) 错误,不能用
3
8
7
整数型
浮点型
复数类型
复数的实部和虚部都是浮点数,且至少有一个虚部
3+4j,8-7j,0.0j,1j
用于判断逻辑的结果,如True,False
,大写.
使用方式:from decimal import Decimal
使用方式:from fractions import Fraction
不可变序列.数据不能变.字符串,元组,字节序列
字符串,‘abcd’,‘super’,’’‘z’’’
元组,写在圆括号中,用逗号分隔一组数据.(1,2,‘t’)类型可以不同
字节序列.以’b’开头的字符串. bytes.decode(“utf-8”)
可变序列.列表,字节数组
列表,在一对方括号中用逗号隔开的若干数据.可以套.数据类型可以不同. [1,1.5,‘tst’,[1,5]]
字节数组,可以修改的字节序列. bytearray(str,‘utf-8’). 如何转回str?decode
集合数据类型.没有顺序且不能重复.大括号括起来,逗号隔开.
子弹数据类型:键与值,‘key’:‘value’.大括号括起来,中间逗号隔开.
from decimal import Decimal
a = Decimal(1) / Decimal(3)
print(a,type(a),sep=', ')
from fractions import Fraction
#Fraction(numberator=0,denominator=1)
a = Fraction(5,4)
print(a)
#Fraction(other_fraction)
b = Fraction(a)
print(b)
#Fraction(float)
c = Fraction(1.25)
print(c)
#Fraction(string)
d = Fraction("10/8")
print(d)
e = Fraction("1.231231")
print(e)
print(a/b)
print()#开始测试负数
print(2 + 1j)
0.3333333333333333333333333333,
5/4
5/4
5/4
5/4
1231231/1000000
1
(2+1j)
#字节序列
str1 = 'abcd字节序列'
print(str1)
a = str1.encode("utf-8")
print(a)
a = str1.encode("gb2312")
print(a)
print(type(a))
for t in a:
print(t,end="\t")
print("\n")
b = bytearray(str1,'gb2312')
print(b)
print(type(b))
b[4] = 0xd8
print(b)
print(b.decode('gb2312'))
abcd字节序列
b'abcd\xe5\xad\x97\xe8\x8a\x82\xe5\xba\x8f\xe5\x88\x97'
b'abcd\xd7\xd6\xbd\xda\xd0\xf2\xc1\xd0'
97 98 99 100 215 214 189 218 208 242 193 208
bytearray(b'abcd\xd7\xd6\xbd\xda\xd0\xf2\xc1\xd0')
bytearray(b'abcd\xd8\xd6\xbd\xda\xd0\xf2\xc1\xd0')
abcd刂节序列
#Dic
dic = {
'zsf':'tjsg','zwj':'jysg'}
print(dic)
dic['zsf'] = 'tjsg2'
print(dic)
#可以随时加
dic['jyj'] = 'jyzj'
print(dic)
{'zsf': 'tjsg', 'zwj': 'jysg'}
{'zsf': 'tjsg2', 'zwj': 'jysg'}
{'zsf': 'tjsg2', 'zwj': 'jysg', 'jyj': 'jyzj'}
运算:对数据的变换
运算符:运算的符号
操作数:运算数,操作对象
表达式:按运算规则将值,变量和操作符的组合
优先级,操作数
lambda
f = lambda x,y:x+y
可以声明一个匿名函数
m = x if y else z
如果y为真,则取x;否则取z
a or b,a and b,not a
<,<=,>,>=,!=,==
in, not in, is, is not
|, ^, &, >>, <<, ~
,按位或,按位异或,和,右移,左移,取反
+, -, *, /, %, //, **
/
单杠表示float型运算,//
表示整数除法. a**b
,表示 a b a^b ab
从高到低
f = lambda x,y : x+y
print(f(1,2))
print(f(4,5))
3
9
内置函数不需要进行import等,直接使用即可。
abs(x),bin(x),bool(x),int(x),complex([real[,imag]]),ord(x),bytes([source[,encoding[,errors]]])
divmod(a,b)
返回商和余数,是一个元组
x,y = divmod(5,3)
print(x,y,sep = ', ')
1, 2
eval(expression)
expression是一个字符串表达式,返回字符串表达式的值
a = int(input("Please input a : "))
b = int(input("Please input b : "))
s = input("Please input the rule of calculate : ")
c = eval(s)
print(s,"=",c)
Please input a : 123
Please input b : 321
Please input the rule of calculate : a*b + b
a*b + b = 39804
pow(x,y)
等同于x**y
sorted(a)
返回一个有序列表
a = [5,3,1]
s_a = sorted(a)
print(a,s_a,sep = '\n')
[5, 3, 1]
[1, 3, 5]
# 输入三条边求面积
a = float(input("Please input a : "))
b = float(input("Please input b : "))
c = float(input("Please input c : "))
if a<0 or b<0 or c<0:
print('Error')
elif a + b < c or a + c < b or b + c < a:
print("Error")
else:
s = (a + b + c)/2
A = (s*(s-a)*(s-b)*(s-c))**0.5
print(A)
if a<0 or b<0 or c<0:
print('Error')
elif a + b < c or a + c < b or b + c < a:
print("Error")
else:
#print(b**2,c**2,a**2,2*b*c)
cosa = (b**2 + c**2 - a**2) / (2*b*c)
sina = (1-cosa**2)**0.5
#print(sina,cosa)
A = b*c*sina / 2
print(A)
Please input a : 3
Please input b : 4
Please input c : 5
6.0
5.999999999999998
#回文数
s = input("输入数字")
if s.isdigit() == False:
print('Error')
elif s == s[::-1]:
print("Yes")
else:
print('No')
输入数字12521
Yes
#判断闰年
year = int(input("Please input the year : "))
if (year%4 == 0 and y%100 != 0) or (y%400==0):
print("Yes")
else:
print("No")
Please input the year : 2004
Yes
c = input("Please input string : ")
y = (c if c>='a' and c<='z' else chr(ord(c)+32))
# ord(x) 获取x的ASCII值,chr转成char类型
print(y)
Please input string : s
s
mylist = [0,1,2,3,4]
print(mylist[1:10])
print(mylist[0:10])
[1, 2, 3, 4]
[0, 1, 2, 3, 4]
程序按照语句从上到下进行运行就叫顺序结构
from math import *
r = float(input("Please input the r : "))
c = 2 * pi * r
s = pi * r**2
print('c=',c,',r=',r)
if 条件:
满足条件执行的语句
if 条件:
满足条件执行的语句
else:
不满足条件执行的语句
if Case1:
#Do Case1
elif Case2:
#Do Case2
elif Case3:
#Do Case3
elif Case4:
#Do Case4
#...
else:#可以省略
#Other Case
一个分支里面的模块是一个分支,举个例子
if Case1:
if Case2:
#Do case1 and case2
else:
#Do case1 not case2
else:
if Case2:
#Do not case1 and case2
else:
#Do not case1 and not case2
a = int(input('Please input the number: '))
if a > 100:
print("It is bigger than 100!")
a = int(input('\nPlease input the number: '))
if a > 100:
print("It is bigger than 100!")
else:
print("It is smaller than or equal to 100!")
Please input the number: 152
It is bigger than 100!
Please input the number: 135
It is bigger than 100!
score = input("Please input the score : ")
if score.isdigit() == False:
print('Error input')
score = int(score)
if score > 100 or score < 0:
print('Error input')
else:
five_score = 0
if score >= 90:
five_score = 5
elif score >= 80:
five_score = 4
elif score >= 70:
five_score = 3
elif score >= 60:
five_score = 2
else:
five_score = 1
print('Five score is ',five_score)
Please input the score : 85
Five score is 4
#二元方程组
print("ax^2 + bx + c = 0")
a = float(input('a : '))
b = float(input('b : '))
c = float(input('c : '))
if a == 0:
if b == 0:
print('No case! 0x^2 + 0x + c = 0?')
else:
x = - c /b
print('answer = ',x)
else:
beta = b**2 - 4*a*c
if beta >= 0:
x1 = -b + beta**0.5
x2 = -b - beta**0.5
print('x1 = ',x1,',x2 = ',x2)
else:
deta = (-beta)**0.5
real = float('%10.3f'%(-b/(2*a)))
imag = float('%10.3f'%(date/(2*a)))
print('x1 = ',complex(real,imag),',x2 = ',complex(real,-imag))
ax^2 + bx + c = 0
a : 1
b : 2
c : 1
x1 = -2.0 ,x2 = -2.0
#整除,求解可以被整除的数字
n = int(input('Please input a number : '))
k = (n%3==0) + ((n%5==0)<<1) + ((n%7==0)<<2)
if k&1:
print('3',end = '')
if k&2:
print('5',end = '') if (k&1 == 0) else print(',5',end = '')
if k&4:
print('7',end = '') if (k-4 == 0) else print(',7',end = '')
Please input a number : 35
5,7
for i in range(begin,end,step)
,即可枚举i从begin到end,间隔step.
# (b,e)之间,每s计算平方和
b = int(input('b:'))
e = int(input('e:'))
s = int(input('s:'))
sum = 0
for i in range(b,e+1,s):
sum += i * i
print(sum)
b:1
e:10
s:1
385
print(range(1,11,1))
print(range(1,11))
print(range(1,11,2))
range(1, 11)
range(1, 11)
range(1, 11, 2)
for <variable> in <可迭代对象集合>:
<语句块>/<循环体>
else:
<语句块>
mylist = [23,59,1,20,15,5,3]
sum = 0
cnt = 0
for i in mylist:
sum += i
cnt += 1
else:
print('sum=',sum)
print('ave=',sum/cnt)
print('i = ',i)
print('i = ',i)
sum= 126
ave= 18.0
i = 3
i = 3
while <条件>:
<循环体>
else:
<语句块>
else是不满足条件的时候执行的语句
delta = 1
sume = 1
k = 1
print(0.000001 >= 10e-6)
print(0.000001 >= 1e-6)
while delta > 1e-6:
delta /= k
k += 1
sume += delta
print(sume)
False
True
2.7182818011463845
n = int(input('Please input the number : '))
sumn = 0
for i in range(10**(n-1),10**n):
m = i
summ = 0
while m != 0:
summ += (m%10)**n
m //= 10
if i == summ:
print(i)
Please input the number : 3
153
370
371
407
for i in range(1,4):
if i % 2 == 0:
pass
else:
print('It is 2n+1')
print("i is ",i)
print('\n')
for i in range(1,4):
if i % 2 == 0:
continue
else:
print('It is 2n+1')
print("i is ",i)
It is 2n+1
i is 1
i is 2
It is 2n+1
i is 3
It is 2n+1
i is 1
It is 2n+1
i is 3
什么也不做.
中断循环
进行下一次循环
异常:程序中产生的错误
后果:如果产生异常,那么终止现在的程序,然后回溯(Traceback)
try:
<语句块>
except <name1>: #异常 name1
<语句块>
except (<name2>,<name3>): #异常 name2 和 name3 的时候都会被捕获
<语句块>
except <name4> as e: #实例化异常的类,然后进而进行处理
<语句块>
else: #没有异常的时候
<语句块>
finally: #无论是否有异常都确保执行
<语句块>
k = 0
while k < 5:
try:
x = int(input('The first number : '))
y = int(input('The second number: '))
ans = x / y
print('ans = ',ans)
except ValueError:
print('请输入一个整数')
except ZeroDivisionError:
print('除数不能为零')
else:
print('恭喜你成功输入')
finally:
print('本次循环执行完毕')
k += 1
The first number : a
请输入一个整数
本次循环执行完毕
The first number : 1
The second number: 0
除数不能为零
本次循环执行完毕
The first number : 14
The second number: 5
ans = 2.8
恭喜你成功输入
本次循环执行完毕
The first number : 16
The second number: sd2
请输入一个整数
本次循环执行完毕
The first number : 85.5
请输入一个整数
本次循环执行完毕
k = 0
while k < 5:
try:
x = int(input('The first number : '))
y = int(input('The second number: '))
ans = x / y
print('ans = ',ans)
except:
print('????')
k += 1
The first number : a
????
The first number : 1
The second number: 2
ans = 0.5
The first number : 3
The second number: a
????
The first number : 1
The second number: 0
????
The first number : 1
The second number: 5
ans = 0.2
k = 0
while k < 5:
try:
x = int(input('The first number : '))
y = int(input('The second number: '))
ans = x / y
print('ans = ',ans)
except Exception as e:
print(e)
k += 1
The first number : a
invalid literal for int() with base 10: 'a'
The first number : 4
The second number: asd
invalid literal for int() with base 10: 'asd'
The first number : 123
The second number: 0
division by zero
The first number : 554
The second number: 4
ans = 138.5
The first number : asd
invalid literal for int() with base 10: 'asd'
#class name(father):,father必须是Exception
class ComeCustomException(Exception):
pass
raise <class>
class StrExcept(Exception):
pass
class MathExcept(Exception):
pass
while True:
try:
name = input('Please input the name : ')
if len(name) < 2 or len(name) > 20:
raise StrExcept
y = int(input('input the age : '))
if y < 18 or y > 60:
raise MathExcept
p = int(input('input the money : '))
if p < 800:
raise MathExcept
except StrExcept:
print('Name Error')
except MathExcept:
print('Number Error')
except Exception as e:
print(e)
else:
print('name is ',name,'Age is ',y,'Money is ',p,sep='\n')
break
Please input the name : asd
input the age : 15
Number Error
Please input the name : asd
input the age : 20
input the money : 230
name 'MathError' is not defined
Please input the name : 12
input the age : 23
input the money : 23500
name is
12
Age is
23
Money is
23500
assert <test>(,<data>)
#逻辑表达式(,为假的时候提供的表达式)
if not <test>:
raise AssertionError(<data>)
一般格式:
def 函数名(<形参>):
<函数体>
函数名符合标识符规则,形参可没有,多个用逗号隔开,函数体与def要缩进。
可以没有返回值,如果有的话,用return <表达式>
def info(name,age,sex):
print(name,age,sex)
位置绑定。info('张三',18,'男')
关键字绑定。info(age=20,sex='男',name='张三')
形参指定默认值。缺省情况是默认值
def info(name,age,sex='男'):
print(name,age,sex)
用的时候可以info('张三',18)
def 参数名(arg1,arg2,...,*tuple_args,**dic_arg)
pass
*tuple_args
是元组,而不是指针
**dic_arg
是字典,而不是指针
def info(name,sex='男',*t,**d):
print('name : ',name)
print('sex : ',sex)
print('t : ',t)
print('d : ',d)
print()
# print('name : '+name,'sex : '+sex,t,d,sep='\n')
info('张三')
info('张四','女')
info('李六','男',1,2,3)
info('李六',1,2,3)#Problem
info('王八','男',money=4321,friend='李六')
info('陈七','女','a','b','c',money=12345,friend='张三')
#info('陈七','女','a','b','c',money=12345,friend='张三','abc')#运行不了
name : 张三
sex : 男
t : ()
d : {}
name : 张四
sex : 女
t : ()
d : {}
name : 李六
sex : 男
t : (1, 2, 3)
d : {}
name : 李六
sex : 1
t : (2, 3)
d : {}
name : 王八
sex : 男
t : ()
d : {'money': 4321, 'friend': '李六'}
name : 陈七
sex : 女
t : ('a', 'b', 'c')
d : {'money': 12345, 'friend': '张三'}
return a,b
直接逗号分隔即可。返回是一个元组
def f(a,b,c):
sum = a+b+c
avg = sum/3
return sum,avg
s,a = f(1,2,3)
print(s,a)
print(f(30,20,10))
6 2.0
(60, 20.0)
g = lambda x,y,z=0:<表达式>
创建一个匿名函数
g = lambda x,y=0,*t,**d: print(x,y,t,d)
g('snake',123,10,100,1000,oh='???',ho='!!!')
snake 123 (10, 100, 1000) {'oh': '???', 'ho': '!!!'}
函数名(<参数>)
filter(function, sequence)
,过滤函数.
对sequence每个元素执行function,为真则保留,否则删除
返回值是一个迭代器,需要list()才能转化成列表
sorted(iterable, key=None, reverse=False)
,排序函数.
key可以是函数,如果函数返回元组则按顺序当作键值,reverse是翻转,默认为false升序
map(function, sequence[,sequence])
,映射函数.
sequence的个数与function参数对应.依次把sequence的值传进去,然后把返回值当作一个序列返回
返回值是一个迭代器,需要list()才能转化成列表
reduce(function, sequence[, starting_value])
,循环函数.
func必须是一个两参数的函数,先把最初两个放到函数执行,返回值当成下一次执行的第一参数,然后迭代整个sequence.
如果有初始start_value则把start_value当作第一个值执行function.
a = filter(lambda x: x > 0,[-1,0,1,-2,0,2])
print(a)
b = list(a)
print(b)
[1, 2]
a = map(lambda x: x * x + 2,[-1,0,1,-2,0,2])
print(a)
b = list(a)
print(b)
from functools import *
def add(x,y):
print('add1 = ',x,',add2 = ',y,sep='\t')
return x+y
mylist = [1,3,5,7,8]
print(reduce(add,mylist))
print(reduce(add,mylist,10))
add1 = 1 ,add2 = 3
add1 = 4 ,add2 = 5
add1 = 9 ,add2 = 7
add1 = 16 ,add2 = 8
24
add1 = 10 ,add2 = 1
add1 = 11 ,add2 = 3
add1 = 14 ,add2 = 5
add1 = 19 ,add2 = 7
add1 = 26 ,add2 = 8
34
局部变量 优先于 全局变量
global x
打通全局和局部的联系
g = 9
def myAdd():
global g
g = g+1
return g
print(myAdd())
10
相当于函数内部的一个函数
作用域可以参考内部变量的作用域
def f1():
x = y = 2
def f2():
y = 333#这个y的优先级高
print('f2 : x = ',x)#x沿用的是f1的x,相对全局变量
print('f2 : y = ',y)
print()
#define
f2()
#use
print('f1 : x = ',x)
print('f1 : y = ',y)
f1()
f2 : x = 2
f2 : y = 333
f1 : x = 2
f1 : y = 2
把大问题转化成与原问题相似的小问题进行求解。
递归设计要点:
def f(n):
if n is 1:
return 1
return f(n-1) * n
print('f(5) = ',f(5))
f(5) = 120
def Hanoi(n,ch1,ch2,ch3):
if n == 1:
print(ch1, '->', ch3)
else:
Hanoi(n-1,ch1,ch3,ch2)
print(ch1 , '->', ch3)
Hanoi(n-1,ch2,ch1,ch3)
Hanoi(4,'A','B','C')
A -> B
A -> C
B -> C
A -> B
C -> A
C -> B
A -> B
A -> C
B -> C
B -> A
C -> A
B -> C
A -> B
A -> C
B -> C
采用分治思想,把大模块分解成不同功能模块,简化问题。
从信息处理流程出发,分解成不同模块,细化模块,逐层向下分解。
把功能整合到函数中
函数的嵌套定义。可以在函数内部定义一个嵌套函数,把嵌套函数视为一个对象。
直接返回嵌套函数。那么就可以使用这个函数
def make_add(x):
def add(y):
return x + y
return add
add5 = make_add(5)
#add5 等价于 lambda x: return x+5
print(add5(11))
16
定义:若干有共同特征的数据类型的统称。序列在python中相当于若干元素的一个容器。
分类:列表list,元组tuple,字符串string,Unicode字符串,buffer对象,xrange/range对象
通用操作:
索引,s[i]
,从0开始!负数相当于len+i
切片,s[start:end:step]
,按step步长截取[start,end)中的元素.注意不是右],step为负的时候就反向截取,区间还是start > end.
加,s + t
,拼接两个序列.
乘,s * n(int)
,重复拼接一个序列n次.
检索,检索元素x是否属于该序列s,s.index(x[,start[,end]])
,同样如果没有起始可以简化成x in s
,想要同时统计出现的次数s.count(x)
.区间左闭后开.
计算序列长度,len(s)
.
找出最大最小元素,min(s),max(s)
.
s = [0,1,2,3,4,5,6,7,8,9,10,11]
print('s[1] = ',s[1])
a = s[0:10:2]
print('a(changed) = ',a)
print('s(not change) = ',s)
c = s[-4:]
print('c(s[-4:]) = ',c)
c = s[-1:]
print('c(s[-1:]) = ',c)
print('s[0:5:-1] = ',s[0:5:-1])
print('s[5:0:-1] = ',s[5:0:-1])
b = s * 2
print('b = ',b)
print('s.index(5,1,8) = ',s.index(5,1,8))
print('s.index(5,2,8) = ',s.index(5,2,8))
print('s.index(5,5,7) = ',s.index(5,5,7))
#以下都找不到,会返回'ValueError'
try:
print('s.index(5,1,5) = ',s.index(5,1,5))
print('s.index(5,4,5) = ',s.index(5,5,5))
print('s.index(5,1,4) = ',s.index(5,1,4))
print('s.index(5,6,9) = ',s.index(5,6,1))
print('s.index(5,7,9) = ',s.index(5,7,9))
except Exception as e:
print(e)
s[1] = 1
a(changed) = [0, 2, 4, 6, 8]
s(not change) = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
c(s[-4:]) = [8, 9, 10, 11]
c(s[-1:]) = [11]
s[0:5:-1] = []
s[5:0:-1] = [5, 4, 3, 2, 1]
b = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
s.index(5,1,8) = 5
s.index(5,2,8) = 5
s.index(5,5,7) = 5
5 is not in list
创建:声明字符串变量
作为序列操作字符串:上面那些都行
特有操作:
str(),int(),float()
数字与字符串相互转化
格式化生成字符串。'目标字符串%(数据1,数据2,...,数据n)'
。
转换字符串中的格式:%[m]s,%[m]d,%[m,n]f,%[.n]e,%%
查找与替换函数。str.find(sub[,begin[,end]]),str.rfind(sub),str.replace(old,new[,max])
,指定区间(前闭后开),replace那个max是指最多替换的次数。
查找子串位置。str.index(sub)
裁剪指定字符。str.lstrip(strs),str.rstrip(strs),str.strip(strs)
,左右删除。
补充一个删除机制,如果传入的不是一个字符,那么会执行的判断是:
for 边缘字符:
if 边缘字符 in strs:
del 边缘字符
分割字符串。str.split(sep)
,以sep为分隔拆成一个序列
字符大小相关的函数,str.lower()
n,f,s = 62,5.03,'string'
print ( 'n = %5d,n = %-5d,f = %f,s = %s'%(n,n,f,s))
s = 'string string'
print(r"s.lstrip('strsss') = ",s.lstrip('strsss'))
print(r"s.rstrip('ssing') = ",s.rstrip('ssing'))
print(r"s.rstrip('ingss') = ",s.rstrip('ingss'))
print("s.rstrip('ing') = ",s.rstrip('ing'))
print("s.rstrip('gni') = ",s.rstrip('gni'))
print()
print("s.lstrip('sqa') = ",s.lstrip('sqa'))
print("s.lstrip('qsa') = ",s.lstrip('qsa'))
print("s.lstrip('aqs') = ",s.lstrip('aqs'))
s2 = 'www.baidu.com'
print('s2 = ',s2)
print("s2.split('.') = ",s2.split('.'))
n = 62,n = 62 ,f = 5.030000,s = string
s.lstrip('strsss') = ing string
s.rstrip('ssing') = string str
s.rstrip('ingss') = string str
s.rstrip('ing') = string str
s.rstrip('gni') = string str
s.lstrip('sqa') = tring string
s.lstrip('qsa') = tring string
s.lstrip('aqs') = tring string
s2 = www.baidu.com
s2.split('.') = ['www', 'baidu', 'com']
#已知一个字符串包含英文和中文,请把他们单独调出来,组成中文和英文字符串
def is_char(c):
if (c >= 'a' and c <= 'z'):
return True
elif c >= 'A' and c <= 'Z':
return True
return False
s = input('Please input the string : ')
s_eng = ''
s_chi = ''
last_eng = False
for value in s:
if is_char(value):
s_eng = s_eng + value
last_eng = True
else:
if last_eng:
s_eng = s_eng + ' '
s_chi = s_chi + value
last_eng = False
print('English : ',s_eng)
print('Chinese : ',s_chi)
Please input the string : I我am很very利害good
English : I am very good
Chinese : 我很利害
#最长公共子串
list2 = [([0] * 3) for i in range(3)]
print(list2,'\n')
#AC ,SA ,SAT
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
创建:L = [],L = [1,2,'s'],L = [1,'s',[3,'s']]
,用string初始化L = list(str)
作为序列的操作:都有,外加一个相等=
独有操作:
append(obj),extend(seq),insert(index,obj)
pop([index])
,返回并弹出。remove(obj)
删除第一个obj。del list[index]
也是删除…
sort(key=None,reverse=False)
排序,key可以是函数生成的列表,reverse是反转。
[lambda x,y:x+y for x in listx for y in listy if (条件)]
列表推导式,等价于(依次嵌套)
for x in listx:
for y in listy:
if 条件:
return x+y
与if-else连通的时候,if-else构成三目运算符号,而不是与if配对。
#L中删除y相同的元素
L = ['a','b','b','c','d','b','a']
y = ['b','c']
for y0 in y:
while y0 in L:
L.remove(y0)
print(L)
ll = []
for l0 in L:
if l0 not in y:
ll.append(l0)
print(ll)
L2 = list(filter(lambda x:x not in y,L))
print(L2)
L3 = [x for x in L if x not in y]
print(L3)
['a', 'd', 'a']
['a', 'd', 'a']
['a', 'd', 'a']
['a', 'd', 'a']
L = [23,1,43,67,5]
L.sort(key = lambda x: abs(x-10))
print(L)
[5, 1, 23, 43, 67]
多维数组:
创建可以使用列表推导式[[0]*m for i in n]
创建n×m的一个二维数组,append也可以。
调用可以跟x[i][j]
一样调用。
M = [[0]*3 for i in range(5)]
print(M)
M2 = []
for i in range(5):
M2.append([])
for j in range(3):
M2[i].append(0)
print(M2)
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
创建方式:
与list相似,把list中的[]
换成()
即可。
也可以使用tuple(object/list)
把其他东西转化成tuple
mylist = [1,'2','12',3.4]
mytuple = tuple(mylist)
print(mytuple)
(1, '2', '12', 3.4)
#给扑克牌排序
Cards = input("Please input the Cards : ")
Cards = Cards.split(' ')
print(Cards)
def ChineseKey(s):
if s[0:2] == '方块':
return 1
elif s[0:2] == '红桃':
return 2;
elif s[0:2] == '黑桃':
return 3
elif s[0:2] == '梅花':
return 4
else:
return 0
#Cards = sorted(Cards,key=ChineseKey)
Cards.sort(key=ChineseKey)
print(Cards)
def CharKey(s):
if s[2:] == 'J':
return 11
elif s[2:] == 'Q':
return 12
elif s[2:] == 'K':
return 13
elif s[2:] == 'A':
return 1
else:
return int(s[2:])
def MultiKey(s):
return (ChineseKey(s),-CharKey(s))
Cards.sort(key=MultiKey)
print(Cards)
Please input the Cards : 黑桃3 黑桃4 红桃3 红桃5 方块2 方块2
['黑桃3', '黑桃4', '红桃3', '红桃5', '方块2', '方块2']
['方块2', '方块2', '红桃3', '红桃5', '黑桃3', '黑桃4']
['方块2', '方块2', '红桃5', '红桃3', '黑桃4', '黑桃3']
#计算距离矩阵
class Point:
def __init__(self,x,y):
self.x = x
self.y = y
def calcDistance(p1,p2):
return ((p1.x-p2.x)**2 + (p1.y-p2.y)**2)**0.5
import random
PointList=[]
for i in range(5):
PointList.append(Point(random.random(),random.random()))
distanceMatrix = []
for i in range(5):
distanceMatrix.append([])
for j in range(5):
distanceMatrix[i].append(calcDistance(PointList[i],PointList[j]))
print(distanceMatrix)
[[0.0, 0.1642966629347754, 0.2575732551961392, 0.4713882339751961, 0.3818885734144432], [0.1642966629347754, 0.0, 0.28629588918796733, 0.5081969179728099, 0.5280302034664563], [0.2575732551961392, 0.28629588918796733, 0.0, 0.7284777334038702, 0.3607356229914618], [0.4713882339751961, 0.5081969179728099, 0.7284777334038702, 0.0, 0.7366767458854895], [0.3818885734144432, 0.5280302034664563, 0.3607356229914618, 0.7366767458854895, 0.0]]
D = (),D = dict(name='Jack',age=45)
.D[key] = value
D[newkey] = value
del D[key],D.clear()#全删
key in D
for k,v in D
len()
,==
常用函数
keys(),values(),items()
get(key='',default='')
查找key,没有就返回defaultpop(key[,default])
返回key的value并删掉它,没有的话返回defaultupdate(**dic)
更新或者添加元素fromkeys(seq)
,把seq的每个元素当成key,设置为默认初始值.#Dic test
D = {
'a':1,'b':2,'c':3}
print(D.get('a'))
print(D.get('x','No'))
1
No
#演示一波去重
pk = {
'方块':1,'梅花':2,'黑桃':3,'红桃':4}
number = {
'A':14,'J':11,'Q':12,'K':13}
for i in range(11):
number[str(i)] = i
Cards = input("Please input the Cards splited by ',': ")
Cards = Cards.split(',')
Cards.sort(key=lambda x:(pk[x[0:2]],-number[x[2:]]))
print(Cards)
dicCards = {
}
dicCards = dicCards.fromkeys(Cards)
Cards1 = list(dicCards.keys())
print(Cards1)
Please input the Cards : 黑桃3 黑桃4 红桃3 红桃5 方块2 方块2
['方块2', '方块2', '黑桃4', '黑桃3', '红桃5', '红桃3']
['方块2', '黑桃4', '黑桃3', '红桃5', '红桃3']
#词频统计
title = input('Please input the article : ')
sentencesplit = "!\t\n\"()-#@"
for e in sentencesplit:
title = title.replace(e,'.')
sentences = title.split('.')
countWord = {
}
for sentence in sentences:
subsentences = sentence.split(',')
for subsentence in subsentences:
words = subsentence.split(' ')
for word in words:
if word == '':
continue
if word in countWord:
countWord[word] = countWord[word]+1
else:
countWord[word] = 1
listWord = list(countWord.items())
listWord.sort(key=lambda x:x[1],reverse=True)
print(listWord)
Please input the article : As a small girl, many teachers have asked me what do I want to be in the future. My answer is always to be a teacher. It is my dream and I study so hard to realize it. Being a teacher can pass the knowledge to others and guide them to the right way. Thinking about the great contribution I would make, everything is worthy.
[('to', 5), ('the', 4), ('a', 3), ('I', 3), ('is', 3), ('be', 2), ('teacher', 2), ('and', 2), ('As', 1), ('small', 1), ('girl', 1), ('many', 1), ('teachers', 1), ('have', 1), ('asked', 1), ('me', 1), ('what', 1), ('do', 1), ('want', 1), ('in', 1), ('future', 1), ('My', 1), ('answer', 1), ('always', 1), ('It', 1), ('my', 1), ('dream', 1), ('study', 1), ('so', 1), ('hard', 1), ('realize', 1), ('it', 1), ('Being', 1), ('can', 1), ('pass', 1), ('knowledge', 1), ('others', 1), ('guide', 1), ('them', 1), ('right', 1), ('way', 1), ('Thinking', 1), ('about', 1), ('great', 1), ('contribution', 1), ('would', 1), ('make', 1), ('everything', 1), ('worthy', 1)]
#词频统计
title = input('Please input title : ')
words = {
}
for x in (''.join(map(lambda x:x if x.isalpha() else '.',title))).split('.'):
words.update({
x: (words[x]+1 if (x in words) else 1)}) if x!='' else x
print(sorted(list(words.items()),key=lambda x:-x[1])[:10])
Please input title : As a small girl, many teachers have asked me what do I want to be in the future. My answer is always to be a teacher. It is my dream and I study so hard to realize it. Being a teacher can pass the knowledge to others and guide them to the right way. Thinking about the great contribution I would make, everything is worthy.
[('to', 5), ('the', 4), ('a', 3), ('I', 3), ('is', 3), ('be', 2), ('teacher', 2), ('and', 2), ('As', 1), ('small', 1)]
#词频统计-闲得无聊压行版本
title = input('Please input title : ')
words = {
}
no_use = list(filter(lambda x:(words.update({
x: (words[x]+1 if (x in words) else 1)}) if x!='' else None) != None,(''.join(map(lambda x:x if x.isalpha() else '.',title))).split('.')))
print(sorted(list(words.items()),key=lambda x:-x[1])[:10])
Please input title : As a small girl, many teachers have asked me what do I want to be in the future. My answer is always to be a teacher. It is my dream and I study so hard to realize it. Being a teacher can pass the knowledge to others and guide them to the right way. Thinking about the great contribution I would make, everything is worthy.
[('to', 5), ('the', 4), ('a', 3), ('I', 3), ('is', 3), ('be', 2), ('teacher', 2), ('and', 2), ('As', 1), ('small', 1)]
#词频统计-真闲得无聊版本
title = input('Please input title : ')
words = {
}
print(
list(filter(lambda x:x!=[],[
list(filter(
lambda x:(words.update({
x: (words[x]+1 if (x in words) else 1)}) if x!='' else None) != None,
(''.join(map(lambda x:x if x.isalpha() else '.',title))).split('.')
)),
sorted(list(words.items()),key=lambda x:-x[1])]
))[0]
)
Please input title : As a small girl, many teachers have asked me what do I want to be in the future. My answer is always to be a teacher. It is my dream and I study so hard to realize it. Being a teacher can pass the knowledge to others and guide them to the right way. Thinking about the great contribution I would make, everything is worthy.
[('to', 5), ('the', 4), ('a', 3), ('I', 3), ('is', 3), ('be', 2), ('teacher', 2), ('and', 2), ('As', 1), ('small', 1), ('girl', 1), ('many', 1), ('teachers', 1), ('have', 1), ('asked', 1), ('me', 1), ('what', 1), ('do', 1), ('want', 1), ('in', 1), ('future', 1), ('My', 1), ('answer', 1), ('always', 1), ('It', 1), ('my', 1), ('dream', 1), ('study', 1), ('so', 1), ('hard', 1), ('realize', 1), ('it', 1), ('Being', 1), ('can', 1), ('pass', 1), ('knowledge', 1), ('others', 1), ('guide', 1), ('them', 1), ('right', 1), ('way', 1), ('Thinking', 1), ('about', 1), ('great', 1), ('contribution', 1), ('would', 1), ('make', 1), ('everything', 1), ('worthy', 1)]
wos={
}
def HH(x):
print("YES! with ",x)
wos.update({
x:x})
return x
no_use = map(lambda x:HH(x),[i for i in range(3)])
print(list(no_use))
print(wos)
print("\nOther Change!\n")
woss = {
}
def HH(x):
print("YES! with ",x)
woss.update({
x:x})
return x
no_use = map(lambda x:HH(x),[i for i in range(3)])
print(woss)
print(list(no_use))
print("\nOther Change!\n")
wosss = {
}
def HH(x):
print("YES! with ",x)
wosss.update({
x:x})
return x
no_use = list(map(lambda x:HH(x),[i for i in range(3)]))
print(wosss)
print(no_use)
YES! with 0
YES! with 1
YES! with 2
[0, 1, 2]
{0: 0, 1: 1, 2: 2}
Other Change!
{}
YES! with 0
YES! with 1
YES! with 2
[0, 1, 2]
Other Change!
YES! with 0
YES! with 1
YES! with 2
{0: 0, 1: 1, 2: 2}
[0, 1, 2]
set
可变集合,frozenset
不可变集合。
s=set(),s=set(['a','b'],s={i for i in range(10)},s={1,2,3,4}
但是不能s={}
这样是空的map。s.add(obj),s.update(lists or other)
s.discord(obj),s.remove(obj),s.pop(),s.clear()
obj in s
, 长度len(s)
<,<=,>,>=,==,!=
intersection(),union(),difference
交并差是一种对象,提供在某种容器上的遍历元素的方法。
__iter__()
返回迭代器对象本身
__next__()
返回容器中的下一个元素
惰性求值,不需要事先准备好整个迭代过程的所有元素,迭代至某个元素的时候才能获取该元素,可以遍历巨大文件.
迭代器获取方式:it = iter(s)
s = (1,2)
it = iter(s)
print(it.__iter__())
print(it.__next__())
print(it.__next__())
#print(it.__next__()),StopIteration!
it = iter(s)
try:
while True:
val = it.__next__()
print(val)
except StopIteration:
print("finish!")
1
2
1
2
finish!
带有yield的语句,用于产生一系列数据。
调用的时候一次执行到一个yield,相当于单步调试
def counter(start=0):
while True:
yield(start)
start=start+1
print('start = ',start)
def get_01():
yield(0)
yield(1)
g = counter(0)
for i in range(3):
print(g.__next__())
g = get_01()
for i in range(2):
print(g.__next__())
0
start = 1
1
start = 2
2
0
1
def fibonacci():
yield(1)
yield(1)
a,b = 1,1
while(True):
a,b = a+b,a
yield(a)
for num in fibonacci():
if num > 100:
break
print('num= ',num)
num= 1
num= 1
num= 2
num= 3
num= 5
num= 8
num= 13
num= 21
num= 34
num= 55
num= 89
打开:fileObject=open(filename,mode)
,文件名,模式r,w,a,rb,wb.ab,+
关闭:fileObject.close()
自动关闭:with open(filename,mode) as f:
,f = open(filename,mode)
。
检测文件是否存在。打开异常等
try:
open(filename,mode)
except FileNotFoundErrer:
print("")
import os
if not os.path.exists('abc.txt'):
print('file is not exist!')
try:
with open('D:\\NewFile.txt','w+') as f:
f.write('山东\n威海\n')
L = ['文化路','哈尔滨']
f.writelines(L)
newL = [line+'\n' for line in L]
f.writelines(newL)
except Exception as e:
print('Error',e)
"""
山东
威海
文化路哈尔滨文化路
哈尔滨
"""
f.read(n)
,读取n个字节的信息.
f.readline()
,读取一行。
f.write(str)
,写入字符串,返回成功写入的长度
f.writelines(seq)
,写入多个字符串,不自动换行
f.tell()
返回当前位置
f.seek(offset[,whence=0])
移动到指定位置,offset是偏移量,whence是标识.
0代表从文件开头开始算起,1代表从当前位置开始算起,2代表从文件末尾算起.
字节流:以字节位单位的一系列二进制数据为字符流。
struct的功能:将一系列不同的数据封装成一段字节流,或者相反。
pack(fmt,v1,v2,...)
unpack(fmt,string)
calcsize(fmt)
fmt:5s2if
5位长度string,2位长度int,还有一个float.! =
字节对齐符号.
python之struct详解
import struct
def m():
with open('Test.txt','wb') as f:
s1 = '张三丰'.encode('utf-8')
s2 = '张无忌'.encode('utf-8')
byte = struct.pack('!10s12si',s1,s2,128)#不是字符串不用编码
f.write(byte)
with open('Test.txt','rb') as f:
a,b,c = struct.unpack('!10s12si',f.read(12+18+4))
print(a.decode('utf-8','ignore'),b.decode('utf-8','ignore'),c)
m()
张三丰 张无忌 128
import struct
def m():
pathfile = 'tes.bmp'
with open(pathfile,'rb') as f:
a = struct.unpack('2s',f.read(2))
b = struct.unpack('i',f.read(4))
c = struct.unpack('i',f.read(4))
print(a[0].decode(),b[0],c[0])
print(a,b,c)
m()
#https://blog.csdn.net/z307840528/article/details/62421853 位图存储
BM 69310 0
(b'BM',) (69310,) (0,)
pickle实现数据序列化
序列化:将任意数据转化成一系列字节存储到文件之中.反序列化是逆操作.
序列化对象:
pickle.dump(obj,file[,model=0])#最后参数为1/2是二进制存储。
pickle.load(file)#读取
Pickle参考文章
import pickle
data = {
'Jack':[32,'male','market'],'Suan':[28,'femal','AD.']}
L = [1,2,3]
L.insert(1,'zxd')
with open('pickle_test1.txt','wb') as f:
pickle.dump(data,f)
pickle.dump(L,f,1)
with open('pickle_test1.txt','rb') as f:
readin = pickle.load(f)
print(readin)
readin = pickle.load(f)
print(readin)
{'Jack': [32, 'male', 'market'], 'Suan': [28, 'femal', 'AD.']}
[1, 'zxd', 2, 3]
#MP3读取歌词
#encoding:UTF-8
def readLRC(filename):
with open(filename,'r',encoding='UTF-8') as f:
res = {
}
L = f.readline()
while L != '':
if(L[1:3].isdigit() and L[4:6].isdigit() and L[7:9].isdigit() and L[3]==':' and L[6]=='.'):
t1 = ((int(L[1:3])*60+int(L[4:6]))*100 + int(L[7:9]))*100
res[t1] = L[10:].strip()
L = f.readline()
return res
filepath = '得不到你.lrc'
res = readLRC(filepath)
for key in sorted(res):
print(key,res[key])
0 《得不到你》
50000 词/曲/唱:隔壁老樊(樊凯杰)
100000
120000 歌词编辑:孟德良
170000 2019年11月14日
220000
244000 把没有光亮的梦 都留给你
322100 把我的日夜思念 都留给你
389300 我把对你的思绪 整理了千丝万缕
467400 叫醒我的却像 晴天霹雳
523500
554500 我依然在自己 的幻想里 沉溺
631500 你也不必再问我 有多喜欢你
710200 遥远的梦 遥远的你
776800 遥远的爱情 在哪里
842000
859000 得不到你 你却在我心里
931500 想你 整日整夜 都在想你
1009600 得不到你 你喜欢通过黑暗 寻找光明
1089300 等你 我在黑暗的尽头 等你
1163900 wow……
1232000
1247600 等你 我在黑暗的尽头 等你
1317500 等你……
1342000 (Music)
1563400 我依然在自己 的幻想里 沉溺
1637900 你也不必再问我 有多喜欢你
1719000 遥远的梦 遥远的你
1782200 遥远的爱情 在哪里
1845000
1865000 得不到你 你却在我心里
1939300 想你 整日整夜 都在想你
2019200 得不到你 你喜欢通过黑暗 寻找光明
2096600 等你 我在黑暗的尽头 等你
2161400
2173400 得不到你 你喜欢通过黑暗 寻找光明
2249300 等你 我在黑暗的尽头 等你
2323700 等你……
2366300 等你……
2397400 在想你……
2428500
2477900 等你……
2516500 (The end)www.90lrc.cn ★
2540000 ☆谢谢欣赏☆
声明类
class 类名:
成员变量#这里可以直接对它进行初始化
#可以认为是静态函数
成员函数
定义类的对象
对象名 = 类名(属性)
类的变量与函数性质
__xx
是私有变量,其他是共有变量
特殊函数
__init__(self,其他参数)
,self是一个指针,指向自身,可以认为是this
__del__(self)
析构函数.
静态成员和静态方法
它们都是类的,不是实例的
静态方法不需要传入self参数,无法访问实例变量
可以直接通过类名来访问
静态方法定义:
class 类名:
函数变量 = 初始值
@staticmethod
def 函数名():
方法体
print(类名.函数变量)
类名.函数名()
#都可以正常进行运行
Python3 中类的静态方法、普通方法、类方法
一个详解
class per1:
strs = 'Myfirst'
def __init__(self):
self.strs = 'TTT'
#print(strs)#报错,未声明变量
strs = 'TTSSS'
print("YES OK!")
p = per1()
print(per1.strs)
print(p.strs)
YES OK!
Myfirst
TTT
#Demo:Static Attr
class Manager():
#静态属性,所有实例只有一个备份,用户实现--单例模型或者资源管理还是有些用处的
data_set = {
}
access_count = 0
def __init__(self,num):
Manager.data_set['default']={
'name':'init_name',
'data':[num]
}
#成员属性可以与静态属性重名
self.data_set = "I'm not a static one"
#成员方法也可以访问静态属性
def show(self):
print("static:",Manager.getData())
print("instance:",self.data_set)
#静态方法只能访问静态属性
@staticmethod
def getData():
Manager.access_count += 1
return Manager.data_set
def __del__(self):
print('Bye Bye!')
if __name__=="__main__":
#可以直接访问
print(Manager.data_set)
#通过静态成员方法访问
print(Manager.getData())
#通过实例成员方法访问
manager = Manager(5)
Manager.data_set['new key']='a value'
manager.show()
#再看一眼静态属性
print(Manager.getData())
print("count:",Manager.access_count)
#实例化的对象属性
print(manager.__dict__)
del manager
{}
{}
Bye Bye!
static: {'default': {'name': 'init_name', 'data': [5]}, 'new key': 'a value'}
instance: I'm not a static one
{'default': {'name': 'init_name', 'data': [5]}, 'new key': 'a value'}
count: 3
{'data_set': "I'm not a static one"}
Bye Bye!
class 派生类名(基类1,基类2,....):
类体
访问父类中同名函数:
super(type[,object-or-type]).XXX
来具体访问type的父类中的XXX
也可以一个参数都不带,默认从括号顺序查找
class people:
def show(self):
print("YES I am people")
class man(people):
def show(self):
print("YES I am a man")
def peopleshow(self):
super().show()
class manteacher(man,people):
def show(self):
print("YES I am a teacher")
def fathershow(self):
super(manteacher,self).show()
'''
class manteacher2(people,man):
#无法确定父类的深度,因此会报错TypeError , MRO错误
def show(self):
print("YES 222222222")
def fathershow(self):
super(manteacher2,self).show()
'''
people1 =people()
people1.show()
manteacher1 = manteacher()
manteacher1.show()
manteacher1.fathershow()
YES I am people
YES I am a teacher
YES I am a man
抽象类与多态.相当于一个公共接口?不加以实现的virtual函数?
而且必须要求子类重新定义所有的抽象方法
知乎-抽象类参考
短毛兔-参考
需要引入模块:
from abc import ABCMeta,abstractmethod
class myABC(object):
__meteclass__=ABM=ABMdta
@abstractmethod
def draw(self):pass#一个抽象方法
#一切皆文件
import abc #利用abc模块实现抽象类
class All_file(metaclass=abc.ABCMeta):
all_type='file'
@abc.abstractmethod #定义抽象方法,无需实现功能
def read(self):
'子类必须定义读功能'
pass
@abc.abstractmethod #定义抽象方法,无需实现功能
def write(self):
'子类必须定义写功能'
pass
# class Txt(All_file):
# pass
#
# t1=Txt() #报错,子类没有定义抽象方法
class Txt(All_file): #子类继承抽象类,但是必须定义read和write方法
def read(self):
print('文本数据的读取方法')
def write(self):
print('文本数据的读取方法')
class Sata(All_file): #子类继承抽象类,但是必须定义read和write方法
def read(self):
print('硬盘数据的读取方法')
def write(self):
print('硬盘数据的读取方法')
class Process(All_file): #子类继承抽象类,但是必须定义read和write方法
def read(self):
print('进程数据的读取方法')
def write(self):
print('进程数据的读取方法')
wenbenwenjian=Txt()
yingpanwenjian=Sata()
jinchengwenjian=Process()
#这样大家都是被归一化了,也就是一切皆文件的思想
wenbenwenjian.read()
yingpanwenjian.write()
jinchengwenjian.read()
print(wenbenwenjian.all_type)
print(yingpanwenjian.all_type)
print(jinchengwenjian.all_type)
文本数据的读取方法
硬盘数据的读取方法
进程数据的读取方法
file
file
file
__add__(self,rhs) self + rhs
__sub__(self,rhs) self - rhs
__mul__(self,rhs) self * rhs
__truediv__(self,rhs) self/rhs
__floordiv__(self,rhs) self//rhs
__mod__(self,rhs) self % rhs
__pos__(self,rhs) self ** rhs
#可以认为是虚函数?
class Compl:
def __init__(self,r,i):
self.r = r
self.i = i
def __add__(self,c):
return Compl(self.r+c.r,self.i+c.i)
def show(self):
print(self.r,'\t',self.i)
comp1 = Compl(1,2)
comp2 = Compl(4,3)
(comp1 + comp2).show()
5 5
文件名.py是模块
一个类一个块
引入类
import 模块名 或 from 模块名 import 类名
如,a.py中义了A类,在类C中引入了A
import a 或 from a import A
包
一个包含__init__.py的文件夹,称为包
引入包中的模块
import 包名.模块名
模块名.类名
拓展文章:Python包详解
传输层 : 数据段Segment
网络层 : 数据包Packet
数据链路层 : 数据帧Frame
物理层 : 比特Bit
OSI中的应用层,表示层,会话层都对应TCP/IP的应用层.
传输层对应传输层.网络层对应网络层.数据链路层对应网络接口层.
应用层: “你好!”
传输层: “你好”+TCP头部
网络层: “你好”+TCP头部+IP头部
网络链路层: “你好”+TCP头部+IP头部+帧头部
定义:网络通讯的一套程序接口,网络编程的标准.(Berkeley伯克利)
作用:网络通讯基础,相当于一个管道连接发送端和接收端.
基础协议:TCP/UDP
基础函数
socket(family,type[,protocl])
创建一个流式套接字,返回套接字号.
family的两个取值:AF_INET,AF_INET6
对应IPV4/IPV6.
type套接字类型.SOCK_STREAM,SOCK_DGRAM
对应TCP通讯协议和UDP通讯协议.
protocol:与指定家族相关的协议,默认为0.
bind(address)
有端口号的address,将套接字绑定到一个已知的地址及端口号,通常为本地IP地址.
sendto(data(,addr,port))
,发送数据.
data,addr = recvfrom(bufsize)
接收数据
服务端和客户端的流程
服务端: 建立流式套接字,与本地IP绑定,在套接字上写数据只到结束,关闭套接字
客户端:建立流式套接字,在套接字上读写数据,关闭套接字
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.bind(('127.0.0.1',5005))
while True:
data,addr = s.recvfrom(1024)
if not data or data.decode('utf-8') == '1':
print('Client has exited!')
break
print('receoved : ',data,' from ',addr)
print("receoved is : ",data.decode('utf-8'))
s.close()
receoved : b'01' from ('127.0.0.1', 59413)
receoved is : 01
Client has exited!
#启动另一个python程序
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
port = 5005
host = '127.0.0.1'
while True:
msg = input()
if not msg:
break
s.sendto(msg.encode("utf-8"),(host,port))
s.close()
服务器端:
s.listen(backlog)
开始监听TCP连接,backlog为网络最大连接数
s.accept()
接受TCP连接并返回(conn,address)
,conn套接字对象,用于接收和发送数据,address是连接客户端的地址.
客户端:
s.connect(address)
,连接到address处,address = (host,port)共有的:
s.recv(bufsize[,flag])
接收TCP数据,以字符串形式返回,bufsize表示最大接收数据量
s.sendall(bytes[,flag])
完整发送TCP数据
s.settimeout(timeout)
返回当前超时期的值,单位是秒.
#服务器端
from socket import *
from time import ctime
host = '127.0.0.1'
port = 4700
buf = 1024
addr = (host,port)
s = socket(AF_INET,SOCK_STREAM)
s.bind(addr)
s.listen(20)
print('Wait...')
cs,caddr = s.accept()
while True:
print("Connect from : ",caddr)
data = 'Welcome!\n'
cs.sendall(bytes(data,'utf-8'))
data = cs.recv(buf).decode('utf-8')
if not data or data == '0':
break
data = '[%s]%s\r\n'%(ctime(),data)
cs.sendall(bytes(data,'utf-8'))
print(data)
cs.close()
s.close()
Wait...
Connect from : ('127.0.0.1', 55634)
[Tue Jul 14 09:58:07 2020]123
Connect from : ('127.0.0.1', 55634)
[Tue Jul 14 09:58:08 2020]1234
Connect from : ('127.0.0.1', 55634)
[Tue Jul 14 09:58:10 2020]4567
Connect from : ('127.0.0.1', 55634)
[Tue Jul 14 09:58:11 2020]1
Connect from : ('127.0.0.1', 55634)
[Tue Jul 14 09:58:15 2020]1
Connect from : ('127.0.0.1', 55634)
[Tue Jul 14 09:58:16 2020]1
Connect from : ('127.0.0.1', 55634)
#客户端
from socket import *
buf = 1024
addr = ('127.0.0.1',4700)
cs = socket(AF_INET,SOCK_STREAM)
cs.connect(addr)
data = cs.recv(buf).decode('utf-8')
if data:
print(data)
while True:
data = input()
if data:
cs.sendall(bytes(data,'utf-8'))
if data == '0':
break
data = cs.recv(buf).decode('utf-8')
if data:
print(data)
cs.close()