如何在python中打开闭包? [英] How to open a closure in python?

查看:32
本文介绍了如何在python中打开闭包?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了以下面试问题,却不知道如何解决:

I came accross the following interview question and have no idea how to solve it:

def cons(a, b):
    def pair(f):
        return f(a, b)
    return pair

给出一对,例如 cons(6,8),我被要求分别返回 a b ,例如在这种情况下6,分别是8个.

Given a pair, e.g cons(6,8) I am requested to return a and b separetely, e.g in this case 6, 8 respectively.

例如,意思是

def first(pair):
    pass
    #would return pair's `a` somehow

def second(pair):
    pass
    #would return pair's `b` somehow

这怎么办?

推荐答案

您可以尝试:

pair = cons(6, 8)

def first(pair):
    return  pair(lambda x, y: x)

def second(pair):
    return  pair(lambda x, y: y)

print(first(pair))
print(second(pair))

# ouput:
# 6
# 8

这篇关于如何在python中打开闭包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆