每天进步一点点:Python中使用函数作为参数 by oflyhigh

View this thread on steempeak.com
· @oflyhigh ·
$110.08
每天进步一点点:Python中使用函数作为参数
在我的一个Python小脚本中,我有一个变态的需求,在一个函数中调用不同的函数,这个时候最简单的方法就是将待调用的函数作为参数传入。

![](https://steemitimages.com/DQmXQzDMbiUMFVUWX8A9qodarzSPfjvgJH9NufV46enHncb/image.png)
(图源:[bing.com](bing.com))

# 函数也是对象

之所以可以这样操作的原因是因为Python中一切皆是对象,举例说,我们可以定义个简单的函数并打印相关信息:
```
def add(x, y):
        return x + y

print(add)
print(type(add))
print(id(add))
```

上述代码将输出类似如下信息:
><function add at 0xb6b8d618>
<class 'function'>
3065566744

# 函数作为参数

有了上述分析,我们就可以大胆的将函数作为参数传入其它函数中了,下边我们实现了简单的加法(add)、减法函数(sub)。同时我们定义了一个函数计算(calc),这个函数接受一个函数以及其它两个参数。
```
def add(x, y):
        return x + y

def sub(x, y):
        return x - y

def calc(func, a, b):
        return func(a, b)

print(calc(add, 1, 2))
print(calc(sub, 1, 2))
```

可见,我们可以通过调用calc函数,并指定用于进行计算的函数(add或者sub)来计算对应的数值。上述代码输入结果如下:
>3
-1

# 函数参数的可变参数

上述例子中,我们直接在calc函数定义中指定了参数,并传递给其中的函数调用(add或sub),但是如果我们没法确定其内被调用的函数有多少个参数,或者有些参数是关键字参数,可怎么办呢?

答案是很简单的,我们只需将其传入到calc函数即可。

```
def add(x, y):
        return x + y

def add_more(x, y, z):
        return x + y + z

def sub(x, y):
        return x - y

def calc(func, *args, **kwargs):
        return func(*args, **kwargs)

print(calc(add, 1, 2))
print(calc(sub, 1, 2))
print(calc(add_more, 1, 2, 3))
print(calc(add_more, x=1, y=2, z=3))
```

其中:
```
def calc(func, *args, **kwargs):
        return func(*args, **kwargs)
```
第一句代表将位置参数打包给args(tuple类型),将关键字参数打包给kwargs(dict)类型。第二句函数调用括号内则代表将对应的数据解包。

将上述代码改进一下:
```
def add(x, y):
        return x + y

def add_more(x, y, z):
        return x + y + z

def sub(x, y):
        return x - y

def calc(func, *args, **kwargs):
        print(args)
        print(kwargs)
        return func(*args, **kwargs)

print(calc(add, 1, 2))
print()

print(calc(sub, 1, 2))
print()

print(calc(add_more, 1, 2, 3))
print()

print(calc(add_more, x=1, y=2, z=3))
```

结果如下:
>(1, 2)
{}
3
>
>(1, 2)
{}
-1
>
>(1, 2, 3)
{}
6
>
>()
{'x': 1, 'y': 2, 'z': 3}
6

# Python 内置函数

在Python内置函数中,有几个函数使用了函数作为参数,比如:
* map()
`map(function, iterable, ...)`
* filter()
`filter(function, iterable)`
* reduce()
`reduce(function, iterable[, initializer])`

本文就不做深入介绍了。
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , and 71 others
properties (23)
post_id44,448,297
authoroflyhigh
permlink4ckfhr-python
categorypython
json_metadata"{"links": ["bing.com"], "format": "markdown", "app": "steemit/0.1", "image": ["https://steemitimages.com/DQmXQzDMbiUMFVUWX8A9qodarzSPfjvgJH9NufV46enHncb/image.png"], "tags": ["python", "programming", "cn-programming", "learning", "cn"]}"
created2018-04-20 02:45:09
last_update2018-04-20 02:45:09
depth0
children8
net_rshares19,817,018,110,948
last_payout2018-04-27 02:45:09
cashout_time1969-12-31 23:59:59
total_payout_value94.208 SBD
curator_payout_value15.867 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length2,053
author_reputation1,148,153,621,496,884
root_title每天进步一点点:Python中使用函数作为参数
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
author_curate_reward""
vote details (135)
@dangtmaximun ·
the content of programming is awesome.
excellent context.
properties (22)
post_id44,448,485
authordangtmaximun
permlinkre-oflyhigh-4ckfhr-python-20180420t024627885z
categorypython
json_metadata"{"app": "steemit/0.1", "tags": ["python"]}"
created2018-04-20 02:47:03
last_update2018-04-20 02:47:03
depth1
children0
net_rshares0
last_payout2018-04-27 02:47:03
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length57
author_reputation68,478,707,640
root_title每天进步一点点:Python中使用函数作为参数
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
@greentomorrow ·
fossbot voter comment
Hey, just wanted to let you know I gave you an upvote because I appreciate your content!  =D See you around
👎  ,
properties (23)
post_id44,455,953
authorgreentomorrow
permlinkre-oflyhigh-4ckfhr-python-20180420t035805954z
categorypython
json_metadata{}
created2018-04-20 03:58:06
last_update2018-04-20 03:58:06
depth1
children1
net_rshares-32,076,498,836
last_payout2018-04-27 03:58:06
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length107
author_reputation-132,163,372,139
root_title每天进步一点点:Python中使用函数作为参数
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
author_curate_reward""
vote details (2)
@neutralizer ·
# Be advised @oflyhigh
 The comment from @greentomorrow is far from being sincere. It has been identified as being copy/pasted comment spam intended to trick their targets into upvoting them. Please, refrain from doing so. They have been reported to @steemcleaners as well as downvoted and we are giving people a heads-up until they are dealt with. Thank you!
properties (22)
post_id44,506,346
authorneutralizer
permlinkre-re-oflyhigh-4ckfhr-python-20180420t035805954z-20180420t112828
categorypython
json_metadata{}
created2018-04-20 11:28:30
last_update2018-04-20 11:28:30
depth2
children0
net_rshares0
last_payout2018-04-27 11:28:30
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length359
author_reputation602,559,586,074
root_title每天进步一点点:Python中使用函数作为参数
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
@steemit.lover ·
😥😥😥😥
properties (22)
post_id44,460,945
authorsteemit.lover
permlinkre-oflyhigh-4ckfhr-python-20180420t044554129z
categorypython
json_metadata"{"app": "steemit/0.1", "tags": ["python"]}"
created2018-04-20 04:46:00
last_update2018-04-20 04:46:00
depth1
children0
net_rshares0
last_payout2018-04-27 04:46:00
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length4
author_reputation1,104,926,356
root_title每天进步一点点:Python中使用函数作为参数
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
@tsinrong ·
像你学习,每天进步一点点
properties (22)
post_id44,461,448
authortsinrong
permlinkre-oflyhigh-4ckfhr-python-20180420t045057755z
categorypython
json_metadata"{"app": "steemit/0.1", "tags": ["python"]}"
created2018-04-20 04:50:57
last_update2018-04-20 04:50:57
depth1
children0
net_rshares0
last_payout2018-04-27 04:50:57
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length12
author_reputation92,139,201,544
root_title每天进步一点点:Python中使用函数作为参数
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
@superoo7 · (edited)
可能是玩functional太多了,当我写java和python都会用Lambda

Python 3
```
def increase (n): return lambda x: x + n
vals = increase([1])
print(vals(2))
```

然后在lambda都能用filter,map和reduce
properties (22)
post_id44,529,963
authorsuperoo7
permlinkre-oflyhigh-4ckfhr-python-20180420t142319180z
categorypython
json_metadata"{"app": "steemit/0.1", "tags": ["python"]}"
created2018-04-20 14:23:21
last_update2018-04-20 14:27:57
depth1
children0
net_rshares0
last_payout2018-04-27 14:23:21
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length167
author_reputation25,572,770,303,018
root_title每天进步一点点:Python中使用函数作为参数
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
@shine.wong ·
一直很想学python,但是是懒癌患者,略有C#经验和各类C的基础,请教下有没有适合有点变成经验的学习资料(教科书式的一大篇有的没的看不太下去~)
properties (22)
post_id44,926,701
authorshine.wong
permlinkre-oflyhigh-4ckfhr-python-20180423t023418369z
categorypython
json_metadata"{"app": "steemit/0.1", "tags": ["python"]}"
created2018-04-23 02:34:24
last_update2018-04-23 02:34:24
depth1
children0
net_rshares0
last_payout2018-04-30 02:34:24
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length73
author_reputation1,373,339,077,399
root_title每天进步一点点:Python中使用函数作为参数
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
@objc0 ·
最近新出的语言包括其他语言的升级很多都把重点放在了函数式上面,将函数作为一种类型来处理变得越来越流行了。
properties (22)
post_id45,308,975
authorobjc0
permlinkre-oflyhigh-4ckfhr-python-20180425t083446288z
categorypython
json_metadata"{"app": "steemit/0.1", "tags": ["python"]}"
created2018-04-25 08:34:48
last_update2018-04-25 08:34:48
depth1
children0
net_rshares0
last_payout2018-05-02 08:34:48
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length52
author_reputation3,458,508,830
root_title每天进步一点点:Python中使用函数作为参数
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000