| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1985 人关注过本帖
标题:看晕了……求解……
只看楼主 加入收藏
Sornets
Rank: 2
等 级:论坛游民
帖 子:102
专家分:61
注 册:2012-11-22
结帖率:58.82%
收藏
 问题点数:0 回复次数:3 
看晕了……求解……
程序代码:
# Returning functions from functions

# A simple function
def say_hello(greeter, greeted):
  return "Hello, " + greeted + ", I'm " + greeter + "."

# We can use it like this:
print say_hello("Alice", "Bob") # Displays "Hello, Bob, I'm Alice."

# We can also use it in a function:
def produce_greeting_from_alice(greeted):
  return say_hello("Alice", greeted)

print produce_greeting_from_alice("Bob") # Displays "Hello, Bob, I'm Alice."

# We can also return a function from a function by nesting them:
def produce_greeting_from(greeter):
  def greet(greeted):
    return say_hello(greeter, greeted)
  return greet

# Here we create a greeting function for Eve:
produce_greeting_from_eve = produce_greeting_from("Eve")//这里能理解为C中#define produce_greeting_from_eve  produce_greeting_from("Eve") 么?
# 'produce_greeting_from_eve' is now a function:
print produce_greeting_from_eve("Alice") # Displays "Hello, Alice, I'm Eve."

# You can also invoke the function directly if you want:
print produce_greeting_from("Bob")("Eve") # Displays "Hello, Eve, I'm Bob."
2014-02-07 12:35
Sornets
Rank: 2
等 级:论坛游民
帖 子:102
专家分:61
注 册:2012-11-22
收藏
得分:0 
程序代码:
# Using functions in a dictionary instead of long if statements:

# Let's say we have a variable called 'current_action' and we want stuff to happen based on its value:

if current_action == 'PAUSE':
  pause()
elif current_action == 'RESTART':
  restart()
elif current_action == 'RESUME':
  resume()

# This can get long and complicated if there are many values.
# Instead, we can use a dictionary:

response_dict = {
  'PAUSE': pause,
  'RESTART': restart,
  'RESUME': resume
}

response_dict[current_action]() # Gets the correct function from response_dict and calls it//好屌,字符加个括号就成了同名函数了啊!
2014-02-07 12:41
Sornets
Rank: 2
等 级:论坛游民
帖 子:102
专家分:61
注 册:2012-11-22
收藏
得分:0 
回复 2楼 Sornets
请问是这样理解吗?
2014-02-07 12:41
baocaixiong
Rank: 1
等 级:新手上路
帖 子:2
专家分:0
注 册:2014-9-14
收藏
得分:0 
可以这么理解

produce_greeting_from

返回一个闭包
你可以查看
produce_greeting_from_eve.func_closure[0].cell_contents
2014-09-14 23:02
快速回复:看晕了……求解……
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.018236 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved