# func=内存地址
def func():
print(‘from func‘)
func()
输出结果: from func
# func=内存地址
def func():
print(‘from func‘)
f=func # 将func的内存地址传给 f
print(f,func) #输出的是 f func 的内存地址
f() #调用函数 f
输出结果:
<function func at 0x000001CF11CCA0D0> <function func at 0x000001CF11CCA0D0>
from func
# func=内存地址
def func():
print(‘from func‘)
l=[func,]
print(l)
l[0]()
dic={‘k1‘:func}
print(dic)
dic[‘k1‘]()
输出结果:
[<function func at 0x000001B6BC12A0D0>]
from func
{‘k1‘: <function func at 0x000001B6BC12A0D0>}
from func
def func():
print(‘from func‘)
def foo(x): # foo(func), x = func的内存地址
print(x) #先输出func 的内存地址
x() # x=func的内存地址,x()相当于 func()
foo(func) # foo(func的内存地址) #调用函数foo
输出结果:
<function func at 0x000001C3AEF4A0D0>
from func
# func=内存地址
def func():
print(‘from func‘)
def foo(x): # x = func的内存地址
# print(x)
x()
foo(func) #即 foo(func的内存地址)
输出结果:
from func
# func=内存地址
def func():
print(‘from func‘)
def foo(x): # x=func的内存地址
return x # return func的内存地址
res=foo(func) # foo(func的内存地址)
print(res) # res=func的内存地址
res()
输出结果:
<function func at 0x000001C3AEF4A0D0>
from func
def f1():
def f2():
pass
def max2(x,y):
if x > y:
return x
else:
return y
def max4(a,b,c,d):
# 第一步:比较a,b得到res1
res1=max2(a,b)
# 第二步:比较res1,c得到res2
res2=max2(res1,c)
# 第三步:比较res2,d得到res3
res3=max2(res2,d)
return res3
res=max4(1,2,3,4)
print(res)
# 圆形
# 求圆形的求周长:2*pi*radius
def circle(radius,action=0):
from math import pi
def perimiter(radius):
return 2*pi*radius
# 求圆形的求面积:pi*(radius**2)
def area(radius):
return pi*(radius**2)
if action == 0:
return 2*pi*radius
elif action == 1:
return area(radius)
circle(33,action=0)
x=1
def outer():
x=2
def inner():
print(x)
return inner
func=outer()
func() # 结果为2
>>> func.__closure__ (<cell at 0x10212af78: int object at 0x10028cca0>,) >>> func.__closure__[0].cell_contents 2
def f1():
x = 33333333333333333333
def f2():
print(x)
f2()
x=11111
def bar():
x=444444
f1()
def foo():
x=2222
bar()
foo()
输出结果:
33333333333333333333
def f1():
x = 33333333333333333333
def f2():
print(‘函数f2:‘,x)
return f2
f=f1()
# print(f)
# x=4444
# f()
def foo():
x=5555
f()
foo()
输出结果:
函数f2: 33333333333333333333
def f2(x):
print(x)
f2(1)
f2(2)
f2(3)
def f1(x): # x=3
x=3
def f2():
print(x)
return f2
x=f1(3)
print(x)
x()
import requests # 需要事先下载函数模板
传参的方案一:
def get(url):
response=requests.get(url)
print(len(response.text))
get(‘https://www.baidu.com‘)
get(‘https://www.cnblogs.com/linhaifeng‘)
get(‘https://zhuanlan.zhihu.com/p/109056932‘)
传参的方案二:
def outter(url):
# url=‘https://www.baidu.com‘
def get():
response=requests.get(url)
print(len(response.text))
return get
baidu=outter(‘https://www.baidu.com‘)
baidu()
cnblogs=outter(‘https://www.cnblogs.com/linhaifeng‘)
cnblogs()
zhihu=outter(‘https://zhuanlan.zhihu.com/p/109056932‘)
zhihu()
原文:https://www.cnblogs.com/haliluyafeng/p/12536540.html