1 yuankui 2015-07-16 09:46:11 +08:00 高阶函数 not_divisible_3 = not_divisible(3) assert false == not_divisible_3(6) assert false == not_divisible_3(12) assert true == not_divisble_3(11) |
![]() | 2 linnchord 2015-07-16 09:46:36 +08:00 _not_divisible(3)(5) >> True _not_divisible(3)(6) >>False |
![]() | 3 Coyote 2015-07-16 09:50:27 +08:00 ![]() def _not_divisible(n) 返回一个匿名函数 假设 a = _not_divisible(10) 等价于 a = lambda x: x % 10 > 0 现在a就是一个函数 a(1) 就等价于 1 % 10 > 0 最后返回结果 |
![]() | 4 larry618 OP @Coyote 那lambda x: x%n>0 的参数从哪来? 这个函数( _not_divisible(n) )只传入了一个参数啊。。x从哪取值?? |
5 lonelinsky 2015-07-16 10:06:57 +08:00 ![]() @larry618 lambda x:x%n > 0是一个函数,调用这个函数的时候传入x _not_divisible其实返回的是一个函数 |
![]() | 6 churchmice 2015-07-16 10:07:03 +08:00 @larry618 返回的函数传进去的参数 |
![]() | 7 hahastudio 2015-07-16 10:08:04 +08:00 ![]() 1. 函数是一等公民,跟其他的 Class 一样 2. 你可以把 lambda 想象成函数定义,类似 def foo(x): return x % n > 0 3. x 等待你给值啊,_not_divisible(n)(x) |
![]() | 8 Coyote 2015-07-16 10:14:41 +08:00 ![]() @larry618 第一次调用传入了参数n =10 , 返回的结果是 lambda x: x % 10 >0 这个时候x并没有传参, 假设 a = _not_divisible(10) 此时的 a并不是一个数据类型, 而是一个函数 当你执行 a(1)的时候, 才给x进行赋值 2楼的哥们给出了答案 |
![]() | 9 larry618 OP 好哒 谢谢各位 我已经懂了 thanks~ |
![]() | 10 0bit 2015-07-16 14:22:45 +08:00 这种写法挺酷炫的啊 |
11 lidiya 2015-07-16 17:32:49 +08:00 楼主有兴趣的话 也可以看看sundy讲的python http://www.maiziedu.com/course/python/ 个人觉得也不错 |
![]() | 12 mkeith 2015-07-17 16:50:33 +08:00 def _not_divisible(n): ----def fn(x): --------renturn x%n>0 ----return fn |