《Intermediate Python》读书笔记

(一)、语法

1. 对象自省

所谓的对象自省就是判断一个对象的类型的能力。例如python自带的dir函数

#当dir函数没有参数的时候,会返回当前模块定义的所有名称
a = 2
b = 'string'
c = True
dir()

#也可以用来查看对象的方法名字
dir(list)

2. type和instance

type函数语法:type(object) 返回对象类型
id函数:返回对象的内存地址

class A():
    pass

class B(A):
    pass

str1 = 'abcd'
num = 123
a = A()
b = B()
print(type(str1)) 
print(type(num))
print(type(a))
print(type(a))
print( type(a)==type(b))
#instance(ins,cls),第一个参数是实例对象,第二个参数是类名
# type不考虑继承关系,instance会考虑继承关系
isinstance(b, B)
# 以下是运行结果
# <class 'str'>
# <class 'int'>
# <class '__main__.A'>
# <class '__main__.A'>
# False
# True

3. 异常

处理语句是try/except 从句。将可能触发异常的代码放到 try语句中,而处理异常的代码在 except语句里实现。例子如下

try:
    file = open('a.txt', 'r', encoding='utf-8')
except IOError as e:
    print('An IOError occured.{}'.format(e.args[-1]))

处理多个异常的话有两种写法:

#raise可以指定异常
#方法一,把异常写在一个元组里
try:
    file = open('test.txt', 'r', encoding='utf-8')
except (IOError, EOFError) as e:
    print('An error occured: %s' % e.args[-1])

#方法二,写出多个异常,按顺序匹配,只执行一个,也可能不执行
try:
    file = open('test.txt', 'rb')
except EOFError as e:
    print("An EOF error occurred.")
    raise e
except IOError as e:
    print("An error occurred.")
    raise e
#方法三,捕获所有异常
try:
    file = open('a.txt', 'r', encoding='utf-8')
except Exception as e:
    raise

finally从句:不管异常是否发生,finally语句后面的内容都会执行

try:
    file = open('a.txt', 'r', encoding='utf-8')
except Exception as e:
    raise
finally:
	print('流程结束')

4. for-else语句

python中基本的for循环语句为:

for element in list:
	print(element)

但实际上for循环语句也可以跟上一个else语句。当for循环语句正常结束的时候,就会执行else语句后的内容。例如,当我们想要查找10以内的质数和合数的时候就非常方便

#注意缩进,不要把else语句缩进成if-else语句
for n in range(2, 10):
    for x in range(2, n):
        if n%x == 0:
            print('%d 是合数' % n)
            break
    else:
        print('%d 是素数' % n)    

5. 三元运算符

可以使用简单的三元运算符快速判断,也便于维护。

#正常的判断语句
if is_fat:
    state = 'fat'
else:
    state = 'not fat'

#三元运算符
is_fat = True
state = 'fat' if is_fat else 'not fat'

5. global和return

global语句可以让一个变量变为全局变量,例如我们可以在函数中声明一个全局变量,这样函数外部也可以访问。不过大多数情况下,我更推荐用return 语句来返回变量。

def profile():
    name = 'tom'
    age = 18
    return name,age

6. *args和 **kwargs

*args和 **kwargs主要用于函数定义,用来给函数传递不确定的参数。

7. 上下文环境

(二)、函数式编程

1. 枚举

enumerate函数允许我们一边遍历一边计数。同时它还可接受参数,指定初始序号。例子如下:

ls = [1, 2, 3]
for index, value in enumerate(ls):
    print("index %d, value %d" % (index, value))
#运行结果为
#index 0, value 1
#index 1, value 2
#index 2, value 3


my_list = ['red', 'green', 'black', 'brown']
#enumerate可接受参数,指定序号开始数字
for index, value in enumerate(my_list, 2):
    print('index %d, value %s'% (index, value))

#运行结果
# index 2, value red
# index 3, value green
# index 4, value black
# index 5, value brown

#可以利用该函数生成包含序号和值的元组列表
my_list = ['red', 'green', 'black', 'brown']
index_list = list(enumerate(my_list,1))
print(index_list)
#运行结果
# [(1, 'red'), (2, 'green'), (3, 'black'), (4, 'brown')]

2. lambda表达式

它实际上是一个匿名函数,当一个函数只简短使用一次时可以考虑使用它。

#原型 lambda 参数: 操作(参数)
#例子如下
add = lambda x,y,z : x + y + z
print('%d + %d + %d = %d' % (1,2,3,add(1,2,3)))
#运行结果
# 1 + 2 + 3 = 6

#对包含元组的列表排序
num_list = [(3,5), (4,-2), (5,2)]
num_list.sort(key = lambda x:x[1])
print(num_list)
#运行结果
# [(4, -2), (5, 2), (3, 5)]

3. set(集合)数据结构

4. Map,Filter 和 Reduce

map函数会将一个函数映射到一个输入列表中所有元素。例如我需要对列表数据求平方。
注意:map函数默认返回一个迭代器
fileter函数是一个过滤函数,会将输入函数作用在输入列表中每一个元素,当值为true时,才会选择该元素。
而reduce函数直接对整个列表进行计算。

#利用匿名函数和map可以很轻松做到
num = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, num))
print(squared)
# [1, 4, 9, 16, 25]

num = [1, 2, 3, 4, 5]
new_num = filter(lambda x: x>3, num)
print(list(new_num))
# [4, 5]

#reduce需要导入
#reduce函数直接返回一个值,而非迭代器
#reduce函数中的参数函数必须有两个参数
from functools import reduce
num = [1, 2, 3, 4, 5]
mult = reduce(lambda x,y:x*y, num)
print(mult)
# 120

5. 推导式

列表,字典和集合都可以使用推导式,快速生成我们需要的列表。形式是 参数,一个for循环式,后面可以加0-n个for循环或者if语句。

num_list = [x for x in range(12) if x%3 == 0]
num_list
# [0, 3, 6, 9]

#复杂的例子
my_list = [(v,k) for v in range(3) for k in ['red', 'green', 'black'] if v==2]
print(my_list)
# [(2, 'red'), (2, 'green'), (2, 'black')]

(三)、数据结构

1. 生成器

生成器也是一种迭代器,但是你只能对其迭代一次。这是因为它们并没有把所有的值存在内存中,而是在运行时生成值。你通过遍历来使用它们,要么用一个 “for” 循环,要么将它们传递给任意可以进行迭代的函数和结构。大多数时候生成器是以函数来实现的。然而,它们并不返回一个值,而是 yield (暂且译作“生出”)一个值。简单例子如下:

def print_num():
    for i in range(10):
        yield i

num = print_num()
for i in num:
    print(i)
# output:
# 0
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9

#调用内置的方法next来获取下一个数字
#当遍历到最后一个元素之后,next() 会触发一个 StopIteration 的异常
def print_num():
    for i in range(10):
        yield i

num = print_num()
print(next(num))
print(next(num))
print(next(num))
# output:
# 0
# 1
# 2

#iter函数会通过可迭代对象返回一个迭代器对象
str1 = 'apple'
nt = iter(str1)
print(next(nt))
# output:
# a

2. 装饰器

简单来说,装饰器式修改其它函数功能的函数,它可以让我们的代码更加简短。
首先在python中,一切皆为对象。我们先来理解一下函数:

def sayhi(name='lj'):
    return 'hello ' + name
#正常调用函数
rz = sayhi()
print(rz)
# output:
# hello lj

#我们可以把函数赋值给另一个变量
#这里只能写sayhi,而不是sayhi()
dd = sayhi
print(dd())
# output:
# hello lj

#尝试删掉旧的函数
del sayhi
print(sayhi())
# output:
# NameError
print(dd())
# output:
# hello lj

下面我们学习在函数中定义函数:

def outside():
    print('this is out')
    
    def inside():
        print('this is in')
    
    inside()

print(outside())
# output:
# this is out
# this is in

同时,函数还可以作为参数返回:

def hi(name='rz'):
    def greet():
        print('this is greet function')
    
    def welcome():
        print('this is welcome function')
        
    if name == 'rz':
        return greet
    else:
        return welcome
    
a = hi()
print(a())
# output:
# this  is greet function
b = hi('lj')
print(b())
# output:
# this is welcome function

函数也可以作为参数进行传递:

def hi():
    return "hi yasoob!"

def doSomethingBeforeHi(func):
    print("I am doing some boring work before executing hi()")
    print(func())

doSomethingBeforeHi(hi)
#outputs:I am doing some boring work before executing hi()
#        hi yasoob!

通俗来说,装饰器就是在不改变原有函数或对象的前提下,为它增加新的功能。并且python给我们提供了一种简便的写法。

def a_decorater(a_func):
    
    def wrap_the_function():
        print('before executing a_func')
        
        a_func()
        
        print('after executing a_func')
        
    return wrap_the_function

def a_function_requiring_decoration():
    print("I am the function which needs some decoration to remove my foul smell")
    
a_function_requiring_decoration()
# output:
# I am the function which needs some decoration to remove my foul smell

a = a_decorater(a_function_requiring_decoration)
a()
# output:
# before executing a_func
# I am the function which needs some decoration to remove my foul smell
# after executing a_func

# 可以采用@写法,效果是一样的
@a_decorater
def a_function_requiring_decoration():
    print("I am the function which needs some decoration to remove my foul smell")

a_function_requiring_decoration()
# output:
# before executing a_func
# I am the function which needs some decoration to remove my foul smell
# after executing a_func
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值