1.什么是闭包?
闭包的特征?
定义闭包,完成的功能为:传入一个数求和并输出
例如: 传入10 ->输出10
传入15 ->输出25
传入20 ->输出45
# 闭包的作用:
# 隐藏一些不需要暴露给外部使用的变量,减少变量被修改或出错的可能性
# 闭包的要点:
# 1)存在嵌套函数
# 2)将内部函数作为返回值返回
# 3)内部函数使用了外部函数的变量
def out_f():
num = []
def int_f(n):
num.append(n)
return sum(num)
return int_f
int_f1 = out_f()
print(int_f1(10))
print(int_f1(15))
print(int_f1(20))
'''
10
25
45
'''
2.定义一个装饰器:打印函数运行花费的时间
你在执行之前获取一个时间
执行函数
在执行函数之后获取一个时间
去求时间差
time模块
# 定义一个计算执行时间的函数作装饰器,传入参数为装饰的函数或方法
def print_execute_time(func):
from time import time
# 定义嵌套函数,用来打印出装饰的函数的执行时间
def wrapper(*args, **kwargs):
# 定义开始时间和结束时间,将func夹在中间执行,取得其返回值
start = time()
func_return = func(*args, **kwargs)
end = time()
# 打印方法名称和其执行时间
print(f'函数执行花费时间: {end - start}s')
# 返回func的返回值
return func_return
# 返回嵌套的函数
return wrapper
# 定义一个随机数求和的方法,传入参数是随机数的个数,加上刚才定义的装饰器
@print_execute_time
def my_sum(n):
sum = 0
for i in range(n):
sum += i
return sum
print(my_sum(101))
print(my_sum(10000001))
'''
函数执行花费时间: 0.0s
5050
函数执行花费时间: 0.4292259216308594s
50000005000000
'''
3.定义一个类:
要求:包含一个对象属性,且用_(单下划线)命名的
定义一个类方法(装饰器)
定义一个静态方法(装饰器)
定义委托属性(三个类装饰器): 可以访问_命名的属性的值
可以修改_命名的属性的值
可以删除_命名的属性
执行:
实例一个对象
调用类方法(类和对象两种方式)
调用静态方法(类和对象两种方式)
对象.委托属性
对象.委托属性 = value
del 对象.委托属性
class Today:
def __init__(self):
self._data = None
@staticmethod
def static_method(*args, **kwargs):
print("This is static method")
@classmethod
def class_method(cls):
print("This is class method")
@property #委托属性data. property:只能提供访问
def data(self):
return self._data
@data.setter #委托属性的修改:xxx.setter
def data(self, value):
self._data = value
@data.deleter #委托属性的删除:xxx.deleter
def data(self):
del self._data
today = Today()
#调用静态方法:类.方法/对象.方法
Today.class_method()
Today.static_method()
today.class_method()
today.static_method()
print(today.data)
today.data = "data"
print(today.data)
'''
This is class method
This is static method
This is class method
This is static method
None
data
'''