装饰器和偏函数

1. 装饰器

概念:是一个闭包,把一个函数当做参数返回一个替代班的函数,本质上就是一个返回函数的函数。

def func1():
    print('the bryce is handsome')

def outer(func):
    def inner():
        print('******')
        func()
    return inner

#f是func1的加强版本
f=outer(func1)
f()

稍微复杂一点的装饰器:





def outer(func):
    def inner(age):
        if age<0:
            age=0
        func(age)

    return inner

# 使用@符号将装饰器应用到函数

@outer #相当于s=outer(say) 
def say(age):
    print("bryce is %d years old "%(age))
s=outer(say)
s(-10)

* 通用装饰器*


def outer(func):
    def inner(*args,**kwargs):
        #添加修改的功能
        func(*args,**kwargs)
    return inner


@outer
def say(name,age):
    print("my name is %s,i am %d years old "%(name,age))

2. 偏函数

把一个参数固定住,形成一个新的函数

import functools

int3=functools.partial(int,base=2)
print(int3("1010"))


#偏函数
def int2(str,base=2):
    return int(str,base)

print(int2("1010"))

3. 变量的作用域

局部作用域
全局作用域
內建作用域

4. 异常处理

 try.....except.....else

格式:

try:
    语句t
except 错误码 as e:
    语句1
except 错误码 as e:
    语句2
......
except 错误码 as e:
    语句n

else:
    语句e
(finally:)
    ***

断言:

def function(num,div):
    assert(div!=0),"div不能为0"
    return num/div

print(function(10,0))

5. 文件读写

读文件

(1)打开文件
open(path,flag[,encoding,errors])
path:要打开文件的路径
flag:打开方式

r 以只读的方式打开文件,文件的描述符放在文件的开头
rb 以二进制格式打开一个文件用于只读,文件的描述符在文件的开头
r+ 打开一个文件用于读写,文件的描述符放在文件的开头
w 打开一个文件只用于写入,如果该文件已经存在则覆盖,若不存在,则创建新文件
wb 打开一个文件只用于写入二进制,如果该文件已经存在则覆盖,若不存在,则创建新文件
w+ 打开一个文件用于读写,如果该文件已经存在则覆盖,若不存在,则创建新文件
a 打开文件用于追加
a+

encoding:编码方式
errors:错误处理

(2)读文件内容
读取文件的全部内容


path=r"C:Users92924Desktopfile.txt"
f=open(path,"r",encoding="utf-8",errors="ignore")

str=f.read()
print(str)

读取指定字符数


path=r"C:Users92924Desktopfile.txt"
f=open(path,"r",encoding="utf-8",errors="ignore")

str=f.read(10)
print(str)

读取整行


path=r"C:Users92924Desktopfile.txt"
f=open(path,"r",encoding="utf-8",errors="ignore")

str=f.readline()
print(str)

读取所有行,并返回列表


path=r"C:Users92924Desktopfile.txt"
f=open(path,"r",encoding="utf-8",errors="ignore")

str=f.readlines()
print(str)

(3)关闭文件

f.close()

完整简洁写法:


path=r"C:Users92924Desktopfile.txt"
with open(path,'r',encoding='utf-8')as f:
    print(f.read())

写文件

(1)将信息写入缓冲区

f.write("Bryce is a good man")

(2)刷新缓冲区
直接将缓冲区的数据立刻写入文件,而不是被动等待自动的刷新。
(缓冲区满的时候会自动刷新)
f.flush()

完整写文件:

with open(path,'a') as f:
    f.write("good man")

编码与解码

编码:encode()
解码:decode()

原文地址:https://www.cnblogs.com/bryce1010/p/9387008.html