标签:定义函数 please open 类对象 list function pen 执行顺序 urllib
!!!先定义后使用
def funcname(arg1,arg2,....) #funcname = 函数体
'''描述信息'''
函数体
return value
*args:
def foo (x,\*args)
foo(1,2,3,4,5)
** kwargs:
def foo (x,**kwargs)
foo(1,y=2,z=3)
嵌套定义 !!!函数嵌套时的执行顺序
def f1():
x = 1
print('----->f1 ',x)
def f2():
x = 2
print('---->f2 ',x)
def f3():
x = 3
print('--->f3 ',x)
f3()
f2()
f1() >>>----->f1 1;---->f2 2;--->f3 3
函数可以被赋值
def foo():
print('foo')
print(foo)
f = foo
print(f)
把函数当成参数传递
def foo():
print('foo')
def bar(func): >>><function foo at 0x00000000003E3F28>;foo
print(func)
func()
bar(foo)
把函数当成返回值
def foo():
print('foo')
def bar(func):
print(func)
return func
f = bar(foo)
print(f)
把函数当成容器类型的元素去用
def add():
print('==========function add')
def delete():
print('==========function delete')
def search():
print('==========function search')
def change():
print('==========function change')
def tell_msg():
msg = '''
delete:删除
add:添加
search:查询
change:更改
'''
print(msg)
cmd_list = {
'add':add,
'delete':delete,
'search':search,
'change':change
}
while True:
tell_msg()
choice = input('please input your choice: ').strip()
cmd_list[choice]()
x =1
def f1():
x = 1000
def f2():
print(x)
return f2
f = f1()
f()
print(f.__closure__[0])
print(f.__closure__[0].cell_contents)
>>><1000
>>><cell at 0x0000000002177498: int object at 0x0000000001DC9EF0>
>>>1000
from urllib.request import urlopen
def f1(url):
def f2():
print(urlopen(url).read())
return f2
baidu = f1('http://www.baidu.com') #爬网页
baidu()
Day19_名称空间和作用域_函数的嵌套_函数第一类对象的使用_闭包函数
标签:定义函数 please open 类对象 list function pen 执行顺序 urllib
原文地址:http://www.cnblogs.com/sama/p/7868144.html