【问题标题】:Why Python allows def functions inside for loop为什么 Python 允许在 for 循环中使用 def 函数
【发布时间】:2014-04-06 02:36:52
【问题描述】:

我是 Python 的新手,但我尝试了一些东西,但对我来说它是模棱两可的。 为什么 Python 允许在循环中执行函数定义?以及我如何从中受益?

for i in range(2):
  def f():
     print 'f'

  f()

【问题讨论】:

  • 这是 Python 允许 def 任何地方的副作用。如果您愿意,可以将函数定义存储在数组中。

标签: python-2.7


【解决方案1】:

因为 python 是一种高级编程语言,所以您实际上可以返回函数。下面是一个简单但演示的函数。

def multiplier(multiple):
  def f(number):
    return multiple * number
  return f

您可以按如下方式使用该功能:

double = multiplier(2)
print double(3)

将打印 6。

如果您想创建多个函数并将它们存储在列表中或适合您需要的任何其他目的,则同样的概念也适用于循环。

list_of_functions = [] #list of functions
for i in range(2):
  def f(n):
    def printer():
      print "f"*n
    return printer
  list_of_functions.append(f(i+1))

现在您可以调用 list_of_functions[0]() 来打印 'f' 和 list_of_functions[1]() 来打印 'ff'。

【讨论】:

  • 那些ends 在那里做什么,除了导致NameError?另外,please don't use l as a variable name...
  • @HenryKeiter 感谢您注意到您的建议而不是 l,我只是用它来表示一个列表
  • l 的问题在于它看起来很像 1 或 I。“函数列表”的“lof”怎么样?
  • “函数列表”的list_of_functions 怎么样? 可读性很重要。
【解决方案2】:

您可以在任何地方定义函数!因为 Python 以这种方式是动态的,所以您可以在运行时创建函数(和类,以及几乎任何其他东西)。很难想出一个简单的例子来说明为什么要这样做而不显得做作,但用例确实存在。

假设您正在编写一个简单的处理框架。您将允许用户键入命令,这将导致某些功能运行。您可以先定义这些函数,然后将它们全部存储在字典中,以便在获得用户输入时快速查找要运行的适当函数。

def define_functions(letters):
    commands = {} # dictionary of commands
    for letter in letters:
        # Define functions dynamically
        if letter == 'f':
            def _function():
                print('foo')
        elif letter == 'b':
            def _function():
                print('bar')
        elif letter == 'z':
            def _function():
                print('baz')
        else:
            def _function():
                print('Unknown command')

        # Add the new function to the dictionary with the key "n squared"
        commands[letter] = _function
    return commands

commands = define_functions('abcdefghijklmnopqrstuvwxyz')

# Now we have a dictionary of functions.

while True: # loop forever
    # Ask for input and run the specified function!
    func_name = raw_input('Enter the one-letter name of the function to run: ')
    if func_name not in commands:
        print("sorry, that function isn't defined.")
        break

    # Look up the function
    func = commands.get(func_name)

    # Call the function
    func()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-16
    • 2014-05-31
    • 1970-01-01
    • 1970-01-01
    • 2017-11-03
    • 1970-01-01
    • 2014-06-19
    • 1970-01-01
    相关资源
    最近更新 更多