首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往
您找到你想要的搜索结果了吗?
是的
没有找到

python『学习之路03』装饰器

#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2017/11/19 10:45 # @Author : mixiu26 # def foo(): # print("in the foo") # bar() ---->> bar() 方法未定义 # foo() # # def bar(): # print("in the bar()") # def foo(): # print("in the foo()") # bar() ---- >> 正常运行 # foo() # 改进: 内存加载时机是先定义在调用, 函数也是变量,所以呢,代码运行逻辑是从上到下,就是在调用foo()之前, 就先在内存中定义了 # 变量foo,就是将方法体赋给foo, 这里其实什么也没有做, 然后定义bar()这个函数,然后在调用运行foo()这个函数,而在运行它之前 # foo() 和 bar() 这个方法已经存在了, 变量的使用规则就是,先定义在使用, 这里也一样适用 --- >> 函数即'变量' # def foo(): # print("in the foo()") # bar() # ---- >> 正常运行 # def bar(): # print("in the bar()") # foo() # 改进: # def foo(): # print("in the foo()") # bar() # ---- >> 无法正常运行 --- >>因为foo()调用前 bar()还未定义 # foo() # def bar(): # print("in the bar()") # 高阶函数:=========================>> # 1.吧一个函数当做实参传递给另外一个函数: # 2.返回值中包含函数名 # def bar(): # print("in the bar()") # def test1(func): # print(func) # bar的内存地址: <function bar at 0x0000000002452E18> # func() # in the bar() # # test1(bar) # in the bar() # 解释, 首先函数即是变量不解释, 关于变量的使用 ---- >> x = 1; y = x; ----- >> y = 1 # 我们调用test1() --- >>传入了bar ---- 这里的bar == func ---- >>其实就是把bar的内存地址给了func , # 因为bar在内存中作为一个变量来存储方法体, test1中吧bar传给func, 那么这里的func == bar了 --- 他们指向的方法体是一样的只不过在加了个func的引用而已 import time # 函数作为实参传递的高阶函数 # def bar(): # time.sleep(3) # print("in the bar()") # in the bar() # # def test1(func): # start_time = time.time() # func() # sttop_time = time.time() # print("the func run time is %s" %(sttop_time-start_time)) # the func run time is 3.010805130004883 # test1(bar) # in the bar() # 返回值中携带函数的高阶函数: # def bar(): # time.sleep(3) # print("in the bar") # # def test2(func): # print(func) # return func # 注意传值问题: # test2(bar()) ---- >> 这样传值就不符合高阶函数定义, 是要把函数作为实参传递, 如果你带了括号传递的就是bar() 这个方法的返回值 # 而传递: test(bar) ---- >> 这里的bar 传递的就是地址值, 是这个方法体的引用, 所以传递的时候一定要注意 # test2(bar) # 当我们吧bar传过来, test2就开始打印bar的内存地址, 打印完成后又返回bar的内存地址, # 我们将test2的运行结果进行接收: 注意了,我们知道, 函数即是变量. so --- >>ret() <=

03
领券