week4_自学python_decorator

Posted rootid

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了week4_自学python_decorator相关的知识,希望对你有一定的参考价值。

[TOC]
#48.第四周-第01章节-Python3.5-上节内容回顾
#50.第四周-第03章节-Python3.5-装饰器详解
1.装修器定义:装饰器本质是函数,(装饰其它函数)就是为其它函数添加附件功能
2.原则:a)不能修改被装饰函数的源代码
b)不能修改被装饰函数的调用方式
#51.第四周-第04章节-Python3.5-装饰器应用详解
#52.第四周-第05章节-Python3.5-装饰器之函数即变量
#53.第四周-第06章节-Python3.5-装饰器之高阶函数
高阶函数:
a)把一个函数名当作实参传给另一个函数(可以实现装修器中的:不能修改被装饰函数的源代码的情况下为函数增加功能)
```
def bar():
print("in the bar")

def test(func):
print(func)
func()

test(bar)

```

b)返回值中包含函数名(可以实现装修器中的:不修改函数的调用方式)
```
import time
def bar():
time.sleep(3)
print("in the bar")

def test(func):
print(func)
return func

# print(test(bar))
bar = test(bar)
bar() #run bar
```

#54.第四周-第07章节-Python3.5-装饰器之嵌套函数

高阶函数 + 嵌套函数 => 装修器
```
x = 0
def gradpa():
x = 1
def dad():
x = 2
def son():
x = 3
print(x)
son()
dad()
gradpa()

```
#55.第四周-第08章节-Python3.5-装饰器之案例剖析1
装饰器一:
```
import time
def timer(func):
def deco():
start_time = time.time()
func()
stop_time = time.time()
print("the func run time is :{runtime}".format(runtime = (stop_time - start_time)))
return deco

@timer
def test1():
time.sleep(2)
print("in the test1")

test1()
```
#56.第四周-第09章节-Python3.5-装饰器之案例剖析2
装饰器二:解决参数传递问题
```
import time
def timer(func):
def deco(*args,**kwargs):
start_time = time.time()
func(*args,**kwargs)
stop_time = time.time()
print("the func run time is :{runtime}".format(runtime = (stop_time - start_time)))
return deco

@timer
def test1():
time.sleep(2)
print("in the test1")

@timer
def test2(name,age):
time.sleep(2)
print("in the test2:",name,age)

test1()
test2("alex",age = 32)
```
#57.第四周-第10章节-Python3.5-装饰器之高潮讲解









































































以上是关于week4_自学python_decorator的主要内容,如果未能解决你的问题,请参考以下文章

WPhgame2023 week4 Pwn

C++助教篇9_Week4找bugs

COMP9517 week4a Image Segmentation

week4 o1d

BUUCTF NewStarCTF 公开赛赛道Week4 Writeup

BUUCTF NewStarCTF 公开赛赛道Week4 Writeup