Python学习笔记
中文学习网站: 廖雪峰的官网网站https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000
1. Python基础
输入函数:input()
- 输入可以是数字, 字符串, 其他变量, list, tuple. 如果输入多个值,以逗号隔开, 则会转化为tuple.
- input(‘something to print’), 可以在input时先打印一些提示信息
list与tuple
- 删除指定位置的元素, 用pop(i)方法,其中i是索引位置. 不加索引pop()则删除末尾元素
- tuple和list非常类似,但是tuple一旦初始化就不能修改
- 定义只有一个元素的tuple.
>>> t = (1) #t是一个数,因为括号()既可以表示tuple,又可以表示数学公式中的小括号
1
>>> t = (1,) #t是只有一个元素的tuple
(1,)
数据类型转换
>>> int('123')
123
>>> float('12.3')
12.3
>>> str(1.34)
'1.34'
>>> bool(-1) #非零数值,非空list,tuple,非空字符串为True
True
>>> bool(0)
False
>>> bool([0])
True
>>> bool([])
False
>>> bool('')
False
>>> hex(18) #将一个整数转换为一个十六进制字符串
'0x12'
>>> oct(18) #将一个整数转换为一个八进制字符串
'022'
>>> ord('d') #将一个字符转换为它的整数值
100
>>> chr(100) #将一个整数转换为一个字符
'd'
数值操作
>>> 10.0//3 #地板除
3.0
>>> 10.0%3.5 #取余,支持浮点数
3.0
>>> 2**3 #乘方
8
切片操作
- A[a:b:c]: 表示从A[a]到A[b-1]每隔步长c取一个元素.
- a: 起始索引, 缺省为0
- b: 终止索引, 缺省为len(A), “最末端”
- c: 取样间隔,可以没有(只写1个冒号), 缺省为1
>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[1:9:2]
[1, 3, 5, 7]
>>> a[1:9]
[1, 2, 3, 4, 5, 6, 7, 8]
>>> a[::-1] #list翻转
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
迭代遍历
- dict遍历
- 遍历key: for key in d:
- 遍历value: for v in d.values():
- 遍历key-value: for key,val in d.items():
- list遍历
- 遍历元素: for l in list:
- 遍历元素和索引: for i,a in enumerate(list):
2. 高级操作
可变参数
- 在参数前面加了一个*号, 注意: 可变参数必须在固定参数后面
- *list 将列表转换为可变参数
>>> def f(a,*b):
... for i in b:
... a+=i
... return a
...
>>> f(1,2,3,4)
10
>>> f(1)
1
>>> f(1,*[2,3,4]) #列表前面加*表示把列表转成可变参数传进去
10
关键字参数(Python3以上)
- 在参数前面加**号
- 可变参数允许你传入0个或任意个参数,这些可变参数在函数调用时自动组装为一个tuple。而关键字参数允许你传入0个或任意个含参数名的参数,这些关键字参数在函数内部自动组装为一个dict。
- 可以传入任意个数的关键字参数
- **将dict转换为关键字参数
>>> def foo(a,b,**kw):
... print(a,b,kw)
...
>>> foo(1,2)
(1, 2, {})
>>> foo(1,2, key1=1, key2='a')
(1, 2, {'key2': 'a', 'key1': 1})
>>> foo(1,2, **extra)
(1, 2, {'city': 'Beijing', 'job': 'Engineer'})
- 如果要限制关键字参数的名字,就可以用命名关键字参数,例如,只接收city和job作为关键字参数。这种方式定义的函数如下:
>>> def person(name, age, *, city, job):
... print(name, age, city, job)
...
>>> person('Michael', 18, city="Beijing")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: person() missing 1 required keyword-only argument: 'job'
>>> person('Michael', 18, job="student", city="Beijing")
Michael 18 Beijing student
- 限制了关键字参数的名字后, 必须所有关键字的参数都传入, 传入顺序可以打乱. 命名关键字参数可以有缺省值.
参数组合
- 在Python中定义函数,可以用必选参数、默认参数、可变参数、关键字参数和命名关键字参数,这5种参数都可以组合使用。但是请注意,参数定义的顺序必须是:必选参数、默认参数、可变参数、命名关键字参数和关键字参数。
比如定义一个函数,包含上述若干种参数:
def f1(a, b, c=0, *args, **kw):
print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)
def f2(a, b, c=0, *, d, **kw):
print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw)
生成器
- 为了减少列表占用的内存, 可以将对列表的遍历改为对生成器的遍历, 边循环边计算.
- 要创建一个generator,只要把一个列表生成式的[]改成(), 注意: 这不是tuple, 要生成tuple是要用 tuple([])
>>> L = [x * x for x in range(10)]
>>> L
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> g = (x * x for x in range(10))
>>> g
<generator object <genexpr> at 0x1022ef630>
- next(g)可以获取生成器g的下一个返回值, 如果已经到结尾了, 则抛出StopIteration的错误。
- 另一种创建generator的方法,生成器函数:
>>> def fib(max):
... n, a, b = 0, 0, 1
... while n < max:
... yield b
... a, b = b, a + b
... n = n + 1
... return 'done'
...
>>> f = fib(5)
>>> f
<generator object fib at 0x7f4c206597e0>
>>> for i in f:
... print(i)
...
1
1
2
3
5
- yield表示执行到这个位置就中断, 并返回yield的值, 直到下一次迭代(调用了next(g)后)继续执行下面的代码
Iterable与Iterator的区别
- 凡是可作用于for循环的对象都是Iterable类型;
- 凡是可作用于next()函数的对象都是Iterator类型,它们表示一个惰性计算的序列;
- 集合数据类型如list、dict、str等是Iterable但不是Iterator,不过可以通过iter()函数获得一个Iterator对象。
- Python的for循环本质上就是通过不断调用next()函数实现的
for x in [1, 2, 3, 4, 5]:
pass
# 实际上完全等价于:
# 首先获得Iterator对象:
it = iter([1, 2, 3, 4, 5])
# 循环:
while True:
try:
# 获得下一个值:
x = next(it)
except StopIteration:
# 遇到StopIteration就退出循环
break
函数也是一个变量
- 函数也是一个变量, 也可以当做参数传到另一个函数, 相当于函数指针
>>> def add(x, y, f):
... return f(x) + f(y)
...
>>> add(-2,3,abs)
5
map/reduce
- map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素
>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> map(str,a)
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
>>> map(lambda x:x**2+1,a)
[1, 2, 5, 10, 17, 26, 37, 50, 65, 82]
map(f,list)
#等价于
[f(x) for x in list]
- reduce()把一个函数作用在一个序列[x1, x2, x3, …]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算, 其效果就是:
reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
>>> def max(a,b):
... return a if a>b else b
...
>>> reduce(max,[3,4,1,-1,2])
4
#将字符串转整形
>>> d = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
>>> reduce(lambda x,y:x*10+y, map(lambda s:d[s], '54323'))
54323
- 总结: map(f, list), f接收一个参数, 对list中每个元素调用f; reduce(h, list), h接收两个参数, 迭代作用到list中的每个元素.
- filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。
def is_odd(n):
return n % 2 == 1
list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
# 结果: [1, 5, 9, 15]
- sorted()函数对list进行排序
sorted(iterable[, cmp[, key[, reverse]]])
- iterable – 可迭代对象。
- cmp – 比较的函数,这个具有两个参数,参数的值都是从可迭代对象中取出,此函数必须遵守的规则为,大于则返回1,小于则返回-1,等于则返回0。
- key – 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
- reverse – 排序规则,reverse = True 降序 , reverse = False 升序(默认)。
>>> sorted([36, 5, -12, 9, -21], key=abs)
[5, 9, -12, -21, 36]
lambda表达式
f = lambda params_in: params_out - 注意中间的冒号, 冒号前是输入冒号后是输出, 输入可以是多个, 输出只能是一个, 多个输出可以当做一个tuple输出.偏函数
functools.partial的作用就是,把一个函数的某些参数给固定住(也就是设置默认值),返回一个新的函数,调用这个新函数会更简单。>>> import functools
>>> int2 = functools.partial(int, base=2)
>>> int2('1000000')
64
>>> int2('1010101')
85
#创建偏函数时,实际上可以接收函数对象、*args和**kw这3个参数
>>> max2 = functools.partial(max, 10)
# 实际上会把10作为*args的一部分自动加到左边,也就是:
>>> max2(5, 6, 7)
#相当于:
#args = (10, 5, 6, 7)
#max(*args)
10
3. OOP 面向对象编程
类的访问限制
- class中以双下划线开头的变量(如:__private_val)是私有变量, 不能被外部直接访问, 但以双下划线开头和结尾的变量除外(如__name__),这种是特殊变量, 能够被外部直接访问
- 私有变量的实现原理是: python解释器将私有变量改成了_Classname__private_val. 所以如果直接访问 _Classname__private_val是可以访问的, 但强烈不推荐这样做, 因为不同版本的Python解释器可能会把__private_val改成不同的变量名.
- 然而直接用a.__private_val=1, 这种赋值是能通过的, 但是注意:这是新建了一个名为__private_val的成员变量, 并不是原来的私有变量(已经被改名成了_Classname__private_val)
- __slots__ 限制用户能对类添加的属性.
class Student(object):
__slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称
>>> s.age = 25 # 绑定属性'age'
>>> s.score = 99 # 绑定属性'score'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Student' object has no attribute 'score'
注意:__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的
给实例绑定方法
- 通常是直接对类添加方法, 但python支持只对实例绑定方法
>>> def set_age(self, age): # 定义一个函数作为实例方法
... self.age = age
...
>>> from types import MethodType
>>> s.set_age = MethodType(set_age, s) # 给实例绑定一个方法
>>> s.set_age(25) # 调用实例方法
>>> s.age # 测试结果
25
- 实例属性只对当前实例生效, 类属性对类和所有类的实例生效
@property装饰器
- 读接口用@property装饰, 写接口用@score.setter装饰,score是需要装饰的接口名字.
- 尽管是函数, 但调用时不需要带括号, 把它当做一个变量进行访问. 如果没有定义写接口, 则该”变量”只读, 不可写.
- 注意: 必须要先定义@property才能定义写接口.
class Student(object):
#get接口
@property
def score(self):
return self._score
#set接口
@score.setter
def score(self, value):
if not isinstance(value, int):
raise ValueError('score must be an integer!')
if value < 0 or value > 100:
raise ValueError('score must between 0 ~ 100!')
self._score = value
>>> s = Student()
>>> s.score = 60 # OK,实际转化为s.set_score(60)
>>> s.score # OK,实际转化为s.get_score()
60
>>> s.score = 9999
Traceback (most recent call last):
...
ValueError: score must between 0 ~ 100!
实例属性与类属性的区别
实例属性是在类中定义,可以通过类或实例访问,但如果给实例绑定一个同名的属性,实例属性会把类属性覆盖掉。
如下例子中,当调用s.name = ‘Michael’时,s中其实有两个同名的name属性,一个是类属型(“Student”),一个是实例属性(“Michael”),实例属性会将类属性覆盖掉,直到它被删掉。
>>> class Student(object):
... name = 'Student'
...
>>> s = Student() # 创建实例s
>>> print(s.name) # 打印name属性,因为实例并没有name属性,所以会继续查找class的name属性
Student
>>> print(Student.name) # 打印类的name属性
Student
>>> s.name = 'Michael' # 给实例绑定name属性
>>> print(s.name) # 由于实例属性优先级比类属性高,因此,它会屏蔽掉类的name属性
Michael
>>> print(Student.name) # 但是类属性并未消失,用Student.name仍然可以访问
Student
>>> del s.name # 如果删除实例的name属性
>>> print(s.name) # 再次调用s.name,由于实例的name属性没有找到,类的name属性就显示出来了
Student
绑定方法与__slots__
给实例绑定一个方法,注意:
- 绑定实例方法不能直接进行函数赋值,因为需要传入对象实例。
- 另外,实例方法只对单个实例起作用。
>>> def set_age(self, age): # 定义一个函数作为实例方法
... self.age = age
...
>>> from types import MethodType
>>> s.set_age = MethodType(set_age, s) # 给实例绑定一个方法
给类绑定方法:直接赋值,但函数第一个参数必须为self
- 类绑定方法对所有实例起作用,而且不需要重新实例化,之前创建的实例也起作用
>>> def set_score(self, score):
... self.score = score
...
>>> Student.set_score = set_score
使用__slots__可以限制添加实例的属性(包括变量 和方法)
类中的特殊函数
- __init__:类的初始化函数/构造函数
- __slot__:限制类及其实例的可添加属性
- __len__: 返回长度,支持len()函数,它自动去调用该对象的__len__()方法
- __str__: print()一个实例时,会调用该函数
- __repr__:直接显示变量调用该函数,为调试服务的
s = Student()
print(s) #调用__str__
s #调用__repr__
- __iter__: 如果一个类想被用于for … in循环,类似list或tuple那样,就必须实现一个__iter__()方法,该方法返回一个迭代对象,然后,Python的for循环就会不断调用该迭代对象的__next__()方法拿到循环的下一个值,直到遇到StopIteration错误时退出循环。
class Fib(object):
def __init__(self):
self.a, self.b = 0, 1 # 初始化两个计数器a,b
def __iter__(self):
return self # 实例本身就是迭代对象,故返回自己
def __next__(self):
self.a, self.b = self.b, self.a + self.b # 计算下一个值
if self.a > 100000: # 退出循环的条件
raise StopIteration()
return self.a # 返回下一个值
>>> for n in Fib():
... print(n)
...
1
1
2
3
5
...
46368
75025
- __getitem__: 支持list那样按照下标取出元素
class Fib(object):
def __getitem__(self, n):
a, b = 1, 1
for x in range(n):
a, b = b, a + b
return a
>>> f = Fib()
>>> f[0]
1
- __getattr__: 调用对象属性时,如果找不到某个属性,会调用该函数。
- __call__: 支持实例化方法,直接用实例调用方法
class Student(object):
def __init__(self, name):
self.name = name
def __call__(self):
print('My name is %s.' % self.name)
>>> s = Student('Michael')
>>> s() # self参数不要传入, 调用s.__call__()
My name is Michael.
>>> callable(Student())
True
通过callable()函数,我们就可以判断一个对象是否是“可调用”对象。
4. 调试与测试
try except finally
- 执行逻辑:先运行try,遇到异常,则跳出try,如果except捕获异常,则执行except块,最后执行finnally(不管是否异常都会执行)
- Python的错误其实也是class,所有的错误类型都继承自BaseException,except不仅会捕获指定类型的错误,还会捕获其所有子类错误。比如
try:
foo()
except ValueError as e:
print('ValueError')
except UnicodeError as e: #第二个except永远也捕获不到UnicodeError,因为UnicodeError是ValueError的子类,如果有,也被第一个except给捕获了。
print('UnicodeError')
- raise 抛出错误类型。raise语句如果不带参数,就会把当前错误原样抛出。
- 常见的错误类型和继承关系参见:
https://docs.python.org/3/library/exceptions.html#exception-hierarchy
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StopAsyncIteration
+-- ArithmeticError
| +-- FloatingPointError
| +-- OverflowError
| +-- ZeroDivisionError
+-- AssertionError
+-- AttributeError
+-- BufferError
+-- EOFError
+-- ImportError
+-- ModuleNotFoundError
+-- LookupError
| +-- IndexError
| +-- KeyError
+-- MemoryError
+-- NameError
| +-- UnboundLocalError
+-- OSError
| +-- BlockingIOError
| +-- ChildProcessError
| +-- ConnectionError
| | +-- BrokenPipeError
| | +-- ConnectionAbortedError
| | +-- ConnectionRefusedError
| | +-- ConnectionResetError
| +-- FileExistsError
| +-- FileNotFoundError
| +-- InterruptedError
| +-- IsADirectoryError
| +-- NotADirectoryError
| +-- PermissionError
| +-- ProcessLookupError
| +-- TimeoutError
+-- ReferenceError
+-- RuntimeError
| +-- NotImplementedError
| +-- RecursionError
+-- SyntaxError
| +-- IndentationError
| +-- TabError
+-- SystemError
+-- TypeError
+-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
+-- BytesWarning
+-- ResourceWarning
调试方法
- assert, 用法 assert 表达式, 表达式为false时的输出, 运行py文件时加入-O选项可以屏蔽所有断言输出
log, 使用方法
import logging
logging.basicConfig(level=logging.DEBUG, format=’%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s’, datefmt=’%a, %d %b %Y %H:%M:%S’, filename=’myapp.log’, filemode=’w’)#设置log等级,输出格式,输出文件名,默认是输出到屏幕
logging.debug(‘This is debug message’)
logging.info(‘This is info message’)
logging.warning(‘This is warning message’)pdb
- 启动pdb: python3 -m pdb err.py
- n:单步执行
- l:查看当前代码
- p 变量名:查看变量
- q:退出调试
- c:继续执行
- 代码中pdb.set_trace()设置断点