前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python的函数

Python的函数

作者头像
哒呵呵
发布2018-08-06 14:22:20
2650
发布2018-08-06 14:22:20
举报
文章被收录于专栏:鸿的学习笔记鸿的学习笔记

1.函数是第一等对象

最简单的样例:

def hello():

return 'hello'

函数本身是个对象

hello_again=hello

hello_again()

Out[5]: 'hello'

del hello

hello_again()

Out[7]: 'hello'

hello()

Traceback (most recent call last):

NameError: name 'hello' is not defined

可以存储在数据结构里,

funcs=[hello,hello_again]

funcs[0]()

Out[11]: 'hello'

可以传值给另一个函数,

def greet(func):

greeting = func()

print(greeting)

greet(hello)

hello

可以内嵌在另一个函数里可以作为函数值返回

def say_hello(text):

def hello_bay(t):

return t.upper()

return hello_bay(text)

say_hello('hello')

Out[15]: 'HELLO'

2.lambda函数

add = lambda x,y:x+y

add(1,2)

Out[17]: 3

3.装饰器

一个简单的装饰器

def simple_deco(func):

return func

@simple_deco

def hello():

return 'hello'

hello()

Out[19]: 'hello'

装饰器可以理解为输入一个函数返回一个新的函数的函数,python的装饰器是闭包的语法糖。

装饰器可以改变原先函数的行为。

def complex_deco(func):

def inner():

original = func()

modified = original.upper()

return modified

return inner

@complex_deco

def hello():

return 'hello'

hello()

Out[2]: 'HELLO'

遇上多个装饰器的执行顺序,自下而上:

def deco_1(func):

def inner():

return '1+'+func()

return inner

def deco_2(func):

def inner():

return '2+'+func()

return inner

@deco_1

@deco_2

def hello():

return 'hello'

hello()

Out[4]: '1+2+hello'

函数接受参数

def arg_deco(func):

def inner(*args, **kwargs):

return args, kwargs

return inner

@arg_deco

def say(text):

return '{}'.format(text)

say('hello')

Out[8]: (('hello',), {})

实际上参数是传给内部函数的。

4.函数参数的解包

def say(a, b):

return'%s,%s'%(a, b)

正常而言:

say('hello', 'world')

Out[13]: 'hello,world'

除了这个以外,我们也可以加上*,便成了函数参数的解包:

say(*['hello', 'world'])

Out[15]: 'hello,world'

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2018-02-22,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 鸿的学习笔记 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档