学习环境
Python 3.7.9
PyCharm Professional Edition 2020.3.2
JetBrains 2020.3 通杀补丁(学习用,有能力请支持正版)
黑马程序员 python 5.0
Python 基础语法 注释 """ 多行注释1 多行注释2 多行注释3 """ ''' 多行注释1 多行注释2 多行注释3 '''
变量
可改变的量为变量,指向内存的一块空间,当不使用时即会被回收
变量名只能由数字、字母和下划线组成,不能用关键字,不能数字开头,建议不要用中文
变量名尽量见名知意
Python 中常量,一般通过全部大写字母来约定俗成
import keyword print(keyword.kwlist) a = 10 b = 19 a, b = b, a print(a) print(b)
布尔
True:除了 False 都是 True
False:0、0.0、0j、’’、[]、()、set()、{}、None
print(bool(10 )) print(bool(0 )) print(bool(0.0 )) print(bool('0' )) print(bool('' )) print(bool({})) print(bool([])) print(bool(set())) print(bool(0j )) print(bool(None ))
数字
int 整型,二进制,八进制,十进制,十六进制
float 浮点型,小数
conplex 复数,实部+虚部
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 a = 0b11 print(a, type(a)) b = 0o11 print(b, type(b)) c = 0x11 print(c, type(c)) d = 1.1 print(d, type(d)) e = 2e2 print(e, type(e)) f = 1 + 2j print(f, type(f)) g = complex(2 , 3 ) print(g, type(g)) h = True print(h, type(h)) i = False print(i, type(i))
类型转换 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 print(int(10 )) print(int(10.66 )) print(int(True )) print(int(False )) print(int('12345678' )) print(float(10 )) print(float(10.66 )) print(float(True )) print(float(False )) print(float('12345678' )) print(complex(10 )) print(complex(10.66 )) print(complex(True )) print(complex(False )) print(complex('12345678' )) print(complex(1 +2j ))
进制转换 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 a = 0b11 print(int(a)) b = 0o11 print(int(b)) c = 0x11 print(int(c)) d = 3 print(bin(d)) print(oct(d)) print(hex(d))
运算符 算术运算符 print(5 + 2 ) print(5.0 + 2 ) print(5 - 2 ) print(5 * 2 ) print(5 / 2 ) print(4 / 2 ) print(5 // 2 ) print(5 % 2 ) print(5 ** 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 29 30 31 32 33 34 35 num = 1 print(num) a, b, c = 1 , 1.1 , "hello" print(a) print(b) print(c) a = b = 100 print(a) print(b) a = 10 b = 20 a, b = b, a print(a) print(b) a = 10 a *= 1 + 2 print(a)
比较运算符 print(1 == 1 ) print(2 != 1 ) print(3 > 2 ) print(2 < 3 ) print(3 >= 2 ) print(2 <= 3 )
逻辑运算符
流程控制 if语句 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 if 条件1 : 条件1 成立的代码 ......elif 条件2 : 条件2 成立的代码 ......else : 条件都不成立执行的代码 ...... num = 100 if num > 90 : print('A' )elif num > 60 : print('B' )else : print('C' )
三目运算符 a = 10 if 5 > 3 else 5 print(a)
while语句 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 while 条件: 条件成立执行代码1 条件成立执行代码2 ...... n = 1 while n <= 5 : print('hello world' ) n += 1 “”“ hello world hello world hello world hello world hello world ”“” n = 1 while n <= 5 : print('hello world' ) n += 1 else : print('loop done' ) “”“ hello world hello world hello world hello world hello world loop done ”“”
break语句
continue语句
for语句 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 for 临时变量 in 序列: 重复执行代码1 重复执行代码2 ......for word in "hello world" : print(word)""" h e l l o w o r l d """ for word in "hello world" : print(word)else : print("loop done" )""" h e l l o w o r l d loop done """
字符串
可用 "...."
、'...'
以及 """..."""
来表示字符串
字符串可用 /
来转义特殊字符,字符串前加 r
,即表示原始字符串
不可变类型
索引 word = 'Python' print(word[0 ]) print(word[-1 ]) print(word[5 ]) print(word[-6 ])
切片 word = 'Python' print(word[0 :2 ]) print(word[::2 ]) print(word[2 :]) print(word[:]) print(word[3 :]) print(word[1 :8 ])
格式化输出 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 print('{}、{}、{}' .format(1 , 2 , 3 )) print('{0}、{1}、{2}' .format(a, b, 3 )) print('{2}、{1}、{0}' .format(1 , b, c)) print('{x}、{y}' .format(x=3 , y=2 )) print('{0[0]}、{0[1]}' .format([1 , 2 ])) word = 'Python' print(f'I like {word} ' ) print(f'I like {word!s} ' ) print(f'I like {word!a} ' ) print(f'I like {word!r} ' ) print(f'I like {repr(word)} ' )
常用函数 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 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 print(str(1 )) print(str(1.1 )) print(str(True )) print(str([1 , 2 , 3 ])) print(str({"str" : "123" })) str1 = "hello " str2 = "python" print(str1 + str2) print(str1 * 3 ) print(str('hello world' )) print(repr('hello world' )) hello_str = "hello world i like python and c plus and everything hello my friend" print(len(hello_str)) print(hello_str.find("world" )) print(hello_str.find("worlds" )) print(hello_str.find("hello" , 5 , 100 )) print(hello_str.index("world" )) print(hello_str.index("worlds" )) print(hello_str.index("hello" , 5 , 100 )) print(hello_str.count("hello" )) print(hello_str.count("i" )) new_str = hello_str.replace("hello" , "fuck" ) print(hello_str) print(new_str) new_str = hello_str.replace("hello" , "fuck" , 1 ) print(new_str) print(hello_str.split()) print(hello_str.split(maxsplit=1 )) hello_str = " hello world " print(hello_str) print(hello_str.strip()) str_list = ["my" , "name" , "is" , "ReaJason" ] print(" " .join(str_list)) str_dict = {"name" : "ReaJason" , "age" : 18 } print(" " .join(str_dict)) print("hello world" .capitalize()) print("HELLO WORLD" .lower()) print("HELLO WORLD" .islower()) print("hello world" .islower()) print("hello world" .title()) print("hello world" .upper()) print("hello world" .isupper()) print("HELLO WORLD" .isupper()) print("hello world" .ljust(20 )) print("hello world" .ljust(20 , "-" )) print("hello world" .rjust(20 )) print("hello world" .rjust(20 , "-" )) print("hello world" .center(20 )) print("hello world" .center(20 , "-" )) print("hello world" .startswith("hello" )) print("hello world" .startswith("h" )) print("hello world" .startswith("world" )) print("hello world" .endswith("world" )) print("hello world" .endswith("d" )) print("hello world" .endswith("hello" )) print("hello world" .isalpha()) print("1234" .isdigit()) print("1234" .isalnum()) print("hello world" .isalnum()) print("hello1world" .isalnum()) print(" " .isspace())
列表
用 []
组合复合类型(不限定只能一种类型)
使用方括号,其中的项以逗号分隔: [a]
, [a, b, c]
使用一对方括号来表示空列表: []
可变数据类型,可获取,可修改,有序
list1 = [1 , 'Python' , 13.14 , True , 1 +1j , [1 , 2 , 3 ], 'ReaJason' ]
索引 print(list1[0 ]) print(list1[-7 ]) print(list1[-1 ]) print(list1[6 ]) print(list1[5 ][1 ]) list1[5 ][1 ] = 250 print(list1) list1[0 ] = 10 print(list1)
切片 print(list1[0 :2 ]) print(list1[0 :5 :2 ]) print(list1[::-1 ])
遍历 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 list1 = [1 , 'Python' , 13.14 , True , 1 +1j , [1 , 2 , 3 ], 'ReaJason' ]for i in list1: print(i)""" 1 Python 13.14 True (1+1j) [1, 2, 3] ReaJason """ list1 = [1 , 'Python' , 13.14 , True , 1 +1j , [1 , 2 , 3 ], 'ReaJason' ]for index, value in enumerate(list1): print(f"{index} :{value} " )""" 0:1 1:Python 2:13.14 3:True 4:(1+1j) 5:[1, 2, 3] 6:ReaJason """
常用函数 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 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 print(list('12345678' )) list1 = [1 , 2 , 3 ] list2 = ["hello" , "python" ,] print(list1 + list2) print(list2 * 2 ) list2 = [1 , 2 , 3 , 4 , 5 , 1 , 2 ] print(len(list2)) print(list2.count(1 )) list2.reverse() print(list2) list2.sort() print(list2) list2.sort(reverse=True ) print(list2) name_list = ["ReaJason" , "Tom" , "Lucy" , "LiLy" ] print(name_list.index("Tom" )) print(name_list.index("Toms" )) print("ReaJason" in name_list) print("Dazzling" in name_list) print("ReaJason" not in name_list) print("Dazzling" not in name_list) name_list.append("Jack" ) print(name_list) name_list.extend([1 , 2 , 3 , 4 , 5 ]) print(name_list) name_list.insert(1 , "Dazzling" ) print(name_list) del name_list[0 ] print(name_list) del name_list print(name_list) x = name_list.pop() y = name_list.pop(0 ) print(x) print(y) print(name_list) name_list.remove("Tom" ) print(name_list) name_list.clear() print(name_list) name_list2 = name_list.copy() name_list2.append("Dazzling" ) print(name_list) print(name_list2)
列表推导式 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 print(list(range(10 ))) print(list(range(10 , 0 , -1 ))) print(list(range(0 ))) list1 = [i for i in range(10 )] print(list1) print(list(range(10 ))) list1 = [i for i in range(10 ) if i%2 == 0 ] print(list1) arr = [[1 , 2 , 3 ], [4 , 5 , 6 ]] list1 = [j for i in arr for j in i] print(list1)
元组
用 ()
组合复合类型(不限定只能一种类型)
使用一对圆括号来表示空元组: ()
使用一个后缀的逗号来表示单元组: a,
或 (a,)
使用以逗号分隔的多个项: a, b, c
or (a, b, c)
元素数据不可修改,有序
索引切片和 list 一样
tuple1 = (1 , 'Python' , 13.14 , True , 1 + 1j , [1 , 2 , 3 ], 'ReaJason' )
常用函数 print(tuple('12345678' )) print(len(tuple1)) num_tuple = (1 , 1 , 2 , 3 , 4 , 5 ) print(num_tuple.count(1 )) print(num_tuple.count(2 )) print(num_tuple.index(1 )) print(num_tuple.index(6 ))
字典
符号为:{}
数据以键值对形式出现
各个键值对之间用逗号隔开
字典是无序的对象集合,使用键-值(key-value)存储,拥有极快的查询速度
字典是可变类型,键(key)必须使用不可变类型
同一个字典中,键(key)必须是唯一的
字典创建 dict1 = {"name" : "ReaJason" , "age" : 22 , "gender" : "female" } dict2 = dict(name="ReaJason" , age=22 , gender="female" ) dict3 = {} dict4 = dict()
增删改查 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 dict1 = {"name" : "ReaJason" , "age" : 22 , "gender" : "female" } dict1['id' ] = 10 print(dict1) dict1['age' ] = 18 print(dict1) del dict1['name' ] print(dict1) dict1.clear() print(dict1) print(dict1['name' ]) print(dict1['id' ]) print(dict1.get('name' )) print(dict1.get('id' )) print(dict1.get('id' , 1 ))
常用函数 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 dict1 = {"name" : "ReaJason" , "age" : 22 , "gender" : "female" } print(len(dict1)) print("name" in dict1) print("id" not in dict1) print(dict1.keys()) print(dict1.values()) print(dict1.items()) for key,value in dict1.items(): print(f"{key} :{value} " )""" name:ReaJason age:22 gender:female """ dict2 = {"hobby" : "learning" , "id" : 1 } dict1.update(dict2) print(dict1) dict3 = {"name" : "Dazzling" , "age" : 18 , "gender" : "male" } dict1.update(dict3) print(dict1)
字典推导式 cookies = "anonymid=jy0ui55o-u6f6zd; depovince=GW; _r01_=1;" cookies = {cookie.split("=" )[0 ]:cookie.split("=" )[1 ] for cookie in cookies.split("; " )} print(cookies)
集合
多个元素的无序组合,集合是无序的,不支持索引操作
集合元素是唯一的,可用于去重
集合创建 set1 = {1 , 2 , 3 , 1 , 3 , 4 } set2 = set([1 , 2 , 3 , 1 , 3 , 4 ]) set3 = set()
增删改查 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 set1 = {10 , 20 } set1.add(30 ) set1.add(10 ) print(set1) list1 = [10 , 20 , 30 , 40 , 50 ] set1.update(list1) print(set1) set1.remove(10 ) print(set1) set1.remove(10 ) set1.discard(10 ) print(set1) set1.discard(10 ) set1.pop() set1.pop() print(set1) set1.pop() print(10 in set1) print(100 in set1) print(10 not in set1) print(100 not in set1)
函数
将一段具有独立功能的代码块整合到一个整体并命名。在需要的地方调用,实现更高效的代码复用
函数定义参数可有可无,返回值也一样,函数必须先定义后使用
函数设计要尽量短小,嵌套层次不宜过深
函数申明应该做到合理、简单、易于使用
函数参数设计应考虑向下兼容
一个函数只做一件事,尽量保证函数语句粒度的一致性
定义函数 def 函数名(参数1 (可选), 参数2 (可选) ): 函数内代码 ...... return 返回值(可选)def a_add_b (a, b ): return a + b result = a_add_b(10 , 90 ) print(result)
说明文档 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 def a_add_b (a, b ): """ 我是a_add_b的说明文档:一个实现加法的函数 :param a: 参数 1 :param b: 参数 2 :return: 返回值 """ return a + b help(a_add_b)""" Help on function a_add_b in module __main__: a_add_b(a, b) 一个实现加法的函数 :param a: 参数 1 :param b: 参数 2 :return: 返回值 """
变量作用域
def test (): a = 100 print(a) test() print(a)
全局变量,定义在全局,当前 py 文件内都可访问到
a = 100 def test (): print(a) test() print(a)
global(),可被用来表明特定变量生存于全局作用域并且应当在其中被重新绑定
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 a = 100 print(f"全局变量a:{a} " ) def test1 (): a = 200 print(f"test1函数的a:{a} " )def test2 (): global a a = 300 print(f"test2函数的a:{a} " ) test1() test2() print(f"全局变量a:{a} " )
nonlocal(),表明特定变量生存于外层作用域中并且应当在其中被重新绑定
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 def test (): a = 200 def test1 (): print(f"test1函数的a:{a} " ) def test2 (): nonlocal a print(f"test2函数的a:{a} " ) a = 100 print(f"test1函数的a:{a} " ) test1() test2() test()""" test1函数的a:200 test2函数的a:200 test1函数的a:100 """
函数参数
def user_info (name, age, gender ): print(f"name:{name} ,age:{age} ,gender:{gender} " ) user_info("ReaJason" , 18 , "female" ) user_info(18 , "female" , "ReaJason" )
def user_info (name, age, gender ): print(f"name:{name} ,age:{age} ,gender:{gender} " ) user_info(name="ReaJason" , age=18 , gender="female" ) user_info(age=18 , gender="female" , name="ReaJason" ) user_info("ReaJason" , 18 , gender="female" ) user_info(name="ReaJason" , age=18 , "female" )
def user_info (name, age, gender="female" ): print(f"name:{name} ,age:{age} ,gender:{gender} " ) user_info("ReaJason" , 18 ) user_info("ReaJason" , 18 , "male" )
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 def user_info (*args ): print(args) user_info("ReaJason" , 18 , "female" , ["learning" , "gaming" ])def user_info (**kwargs ): print(kwargs) user_info(name="ReaJason" , age=18 , gender="female" , hobby=["learning" , "gaming" ])
lambda函数 a_add_b = lambda a, b: a+b print(a_add_b(10 , 90 ))
map函数 def func (x ): return x ** 2 list1 = [1 , 2 , 3 , 4 , 5 ] list2 = [i ** 2 for i in list1] result1 = map(func, list1) result2 = map(lambda x: x ** 2 , list1) print(result1) print(list(result1)) print(list(result2)) print(list2)
reduce函数 import functools list1 = [1 , 2 , 3 , 4 , 5 , 6 ] result = functools.reduce(lambda x, y: x + y, list1) print(result)
filter函数 def func (x ): return x % 2 == 0 list1 = [1 , 2 , 3 , 4 , 5 , 6 ] list2 = [i for i in list1 if i % 2 == 0 ] result1 = filter(func, list1) result2 = filter(lambda x: x % 2 == 0 , list1) print(result1) print(list(result1)) print(list(result2)) print(list2)
文件操作 文件的读
关于文件读四个模式
r
,以只读的方式打开文件,未找到文件会报错,文件的指针将会放在文件的开头,这是默认模式,r
打开文本文件
rb
,以二进制格式打开一个文件用于只读。文件指针放在文件的开头。这是默认模式,rb
打开非文本文件
r+
,打开一个文件用于读写,准确来说是读并且追加。文件指针将会放在文件的开头
rb+
,以二进制格式打开一个文件用于读写。文件指针将会放在文件的开头
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 48 """ hello world """ f = open("text.txt" , "r" ) content = f.read(5 ) print(content) content = f.read(6 ) print(content) f.close() f = open("text.txt" , "r" ) content = f.read() print(content) f.close()""" hello world hello python """ f = open("text.txt" , "r" ) content = f.readlines() print(content) f.close()""" hello world hello python """ f = open("text.txt" , "r" ) content = f.readline() print(f"第一行{content!r} " ) content = f.readline() print(f"第二行{content!r} " ) content = f.readline() print(f"第三行{content!r} " ) content = f.readline() print(f"第四行{content!r} " ) f.close()
文件的写
关于文件写四个模式
w
,打开一个文件只用于写入。如果文件已存在则先清空后写入,如果没有文件则创建文件
wb
,以二进制格式打开一个文件只用于写入。
w+
,打开一个文件用于读写,巴拉巴拉
wb+
,以二进制格式打开一个文件用于读写,巴拉巴拉
f = open("text1.txt" , "w" ) f.write("hello world" ) f.close()""" hello world """
文件的追加
关于文件写四个模式
a
,打开一个文件用于追加。如果文件存在,新内容将写在文件已有内容之后。文件不存在则创建新文件进行写入。
ab
,a+
,ab+
f = open("text2.txt" , encoding="utf-8" , mode="a" ) f.write("我是第一句" ) f.close()""" 我是第一句 """
其他函数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 """ hello world """ f = open("text.txt" , "r" ) print(f.tell()) content = f.read(5 ) print(content) print(f.tell()) f.close() f = open("text.txt" , "r" ) print(f.tell()) f.seek(6 ) content = f.read() print(content) print(f.tell()) f.close()
with with open("text.txt" , encoding="utf-8" ) as result: print(result.read())""" hello world hello python """
Python 类与对象
类是对一系列具有相同特征 和行为 的事物的统称,是一个抽象概念,特征即属性,行为即方法
对象是类的一个实例,先有类,后有对象
类名遵循大驼峰命名如:HelloWorld
属性和方法可以在类中指定也可以动态添加
面向对象的三个特点:封装、继承、多态
类的定义 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 """ class 类名: 代码 """ class Animal : name = None def eat (self ): print(f"{self.name} 正在吃..." ) cat = Animal() cat.name = "猫" print(cat.name) cat.eat()
魔法方法 init 方法 class Animal : def __init__ (self, name ): self.name = name def eat (self ): print(f"{self.name} 正在吃..." ) cat = Animal("猫" ) print(cat) cat.eat()
str 方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 class Animal : def __init__ (self, name ): self.name = name def __str__ (self ): return f"这是一只{self.name} " def eat (self ): print(f"{self.name} 正在吃..." ) dog = Animal("狗" ) print(dog) dog.eat()
del 方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 class Animal : def __init__ (self, name ): self.name = name def __str__ (self ): return f"这是一只{self.name} " def eat (self ): print(f"{self.name} 正在吃..." ) def __del__ (self ): print(f"{self.name} 死了" ) dog = Animal("狗" ) print(dog) dog.eat()
继承
所有类默认继承 object 类
子类继承父类的所有属性和方法
子类可以重写父类方法
多继承,一个子类可以有多个父类
单继承 class A : def __init__ (self ): self.num = 1 def print_num (self ): print(f"我的数字是:{self.num} " )class B (A ): pass b = B() print(b.num) b.print_num()
重写方法 class A : def __init__ (self ): self.num = 1 def print_num (self ): print(f"A的数字是:{self.num} " )class B (A ): def print_num (self ): print(f"B的数字是:2" ) b = B() b.print_num()
多继承 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 : def __init__ (self ): self.num = 1 def print_num (self ): print(f"A的数字是:{self.num} " )class B : def __init__ (self ): self.num = 2 def print_num (self ): print(f"B的数字是:{self.num} " )class C (B, A ): pass c = C() print(c.num) c.print_num() print(C.__mro__)
多层继承 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 : def __init__ (self ): self.num = 1 def print_num (self ): print(f"A的数字是:{self.num} " )class B : def __init__ (self ): self.num = 2 def print_num (self ): print(f"B的数字是:{self.num} " )class C (B, A ): pass class D (C ): pass d = D() d.print_num() print(D.__mro__)
super() 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 class A : def __init__ (self ): self.num = 1 def print_num (self ): print(f"A的数字是:{self.num} " )class B (A ): def print_num (self ): super(B, self).print_num() print(f"B的数字是:2" ) b = B() b.print_num()
私有属性 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 class A : def __init__ (self ): self.num = 1 self.__score = 100 def print_num (self ): print(f"A的数字是:{self.num} " )class B (A ): def __init__ (self ): super(B, self).__init__() def print_num (self ): print(f"B的数字是:{self.num} " ) b = B() print(b.num) print(b.__score) class A : def __init__ (self ): self.num = 1 self.__score = 100 def print_num (self ): print(f"A的数字是:{self.num} " ) def get_score (self ): return self.__score def set_score (self, score ): self.__score = score a = A() print(a.get_score()) a.set_score(1000 ) print(a.get_score())
多态
多态是指一类事物有多种形态
子类重写父类方法,调用不同子类对象的相同父类方法,可以产生不同的执行结果
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 class Animal : def work (self ): print("动物在叫,人坏掉" )class Cat (Animal ): def work (self ): print("猫在叫,人坏掉" ) class Dog (Animal ): def work (self ): print("狗在叫,人坏掉" )class Person : def work_with_pet (self, cls ): cls.work() cat = Cat() dog = Dog() person = Person() person.work_with_pet(cat) person.work_with_pet(dog)
类方法
当方法中需要使用类对象(如访问私有类属性等),定义类方法
类方法一般和类属性配合使用
class Animal : __name = "动物" @classmethod def get_name (cls ): return cls.__name a = Animal() print(a.get_name())
静态方法
静态方法既不需要传递类对象也不需要传入实例对象
静态方法也能够通过实例对象和类对象去访问
class Animal : @staticmethod def eat (): print("吃就完事了" ) a = Animal() a.eat()
Python 错误和异常 语法错误 语法错误又称解析错误,可能是你在学习Python 时最容易遇到的错误
异常 即使语句或表达式在语法上是正确的,但在尝试执行时,它仍可能会引发错误。 在执行时检测到的错误被称为 异常,异常不一定会导致严重后果。
try : 可能出现异常的代码except 异常类型: 出现异常之后执行的代码try : f = open("text.txt" , "r" )except : f = open("text.txt" , "w" )
捕获指定异常 try : print("12345" ) f = open("123.txt" , "r" ) print("1111" ) print(num) except (NameError, IOError) as result: print("产生错误了" ) print(result)""" 12345 产生错误了 [Errno 2] No such file or directory: '123.txt' """
捕获所有异常 try : print("12345" ) f = open("123.txt" , "r" ) print("1111" ) print(num)except Exception as result: print("产生错误了" ) print(result)""" 12345 产生错误了 [Errno 2] No such file or directory: '123.txt' """
else 语句
finally 语句
自定义异常 class PhoneNumError (Exception ): def __init__ (self, phone ): self.phone = phone def __str__ (self ): return f"{self.phone} ,手机位数错误,应为11位" try : phone_num = "1029321212" if len(phone_num) < 11 : raise PhoneNumError(phone_num)except Exception as e: print(e)
Python 模块与包 模块 模块是一个包含Python定义和语句的文件。文件名就是模块名后跟文件后缀 .py
自定义模块名尽量不要与已有模块同名
模块的导入 import 模块名import 模块名1 ,模块名2 from 模块名 import 模块内函数from 模块名 import * import 模块名 as 别名from 模块名 import 模块内函数 as 别名
模块搜索顺序
当前目录
python 环境变量默认目录下
python 默认路径
包 包是一种通过用“带点号的模块名”来构造 Python 模块命名空间的方法,将有联系的模块组织到一个文件夹,且含有 __init__
文件
导入包 import 包名.模块名from 包名 import 模块名