有没有办法将函数存储在列表或字典中,以便通过索引(或键)调用时执行存储的函数?
比如,我试过像这样的东西,但并没有成功:
mydict = {
'funcList1': [foo(), bar(), goo()],
'funcList2': [foo(), goo(), bar()]}
有没有什么结构可以实现这样的功能呢?
我明白,我当然可以用一堆 def
语句来做到这一点:
def func1():
foo()
bar()
goo()
但是我需要的语句数量越来越多,变得很难管理和记住。如果能把它们整齐地放在一个字典里,偶尔查看一下键就好了。
3 个回答
在编程中,有时候我们需要让程序在特定的条件下执行某些操作。比如说,当用户输入一个数字时,我们可能希望程序根据这个数字来决定接下来要做什么。这种情况下,我们就会用到“条件语句”。
条件语句就像是一个分岔路口,程序在这里会根据你给出的条件选择不同的路径。如果条件满足,程序就会执行某个操作;如果不满足,程序则会执行另一个操作。
举个简单的例子:假设你在写一个程序,让它判断一个数字是正数、负数还是零。你可以用条件语句来检查这个数字,然后告诉用户结果。这样,程序就能根据用户输入的不同,给出不同的反馈。
总之,条件语句是编程中非常重要的一部分,它帮助程序根据不同的情况做出不同的反应。
# Lets say you have 10 programs or functions:
func_list = [program_001, program_002, program_003, program_004, program_005,
program_006, program_007, program_008, program_009, program_010]
choose_program = int(input('Please Choose a program: ')) # input function number
func_list[choose_program - 1]()
操作函数
在Python中,函数被视为“头等对象”,这意味着它们可以像其他任何对象一样用于各种目的。具体来说,函数可以:
- 用
=
赋值给名字(实际上,def
语句本身就是一种赋值方式) - 作为参数传递给其他函数
- 从一个函数中
return
出来 - 有属性,可以用
.
语法查看(实际上,Python允许修改某些属性并赋予新的属性;当然,并不是所有对象都可以这样做) - 参与表达式(调用函数本身就是一种表达式;函数调用的语法在概念上是一个作用于函数的操作符)
- 最重要的是:可以存储在其他容器对象中,比如列表和字典
在问题中提到的失败尝试的问题在于它们立即调用了函数。就像其他对象一样,Python代码可以通过名字引用一个函数(作为对象)。函数的名字不包括括号;写foo()
意味着现在就调用这个函数,并返回结果(即函数返回的内容)。
示例
# Set up some demo functions
def foo():
print('foo function')
def bar():
print('bar function')
def goo():
print('goo function')
# Put them into containers
function_sequence = [foo, bar, goo]
function_mapping = {'foo': foo, 'bar': bar, 'goo': goo}
# Access them iteratively
for f in function_sequence:
# Each time through the loop, a different function is bound to `f`.
# `f` is thus a name for that function, which can be used to call it.
f()
# Access one by lookup, and call it.
# The lookup gives us an object which is a function;
# therefore it can be called with the function-call syntax
to_call = input('which function should i call?')
function_mapping[to_call]()
这些函数的名字是foo
、bar
和goo
;用这些名字可以像操作其他有名字的东西一样操作它们。写foo()
并没有什么特别之处,它并不要求使用def
语句中的名字。实际上,根本不需要使用名字,就像进行乘法运算时,可以使用从容器中查找的值、字面值,或者从其他表达式计算出的值一样。
只要有一个表达式能计算出一个函数对象,它就可以作为函数调用表达式的子表达式。
扩展
lambda
Python的lambda
语法创建的对象与普通函数是同类型的。这个语法限制了生成的函数能做的事情,并且它们会有一个特殊的__name__
属性(因为在编译时没有def
语句来指定名字);但除此之外,它们就是普通的函数,可以以相同的方式进行操作。
def example_func():
pass
# A list containing two do-nothing functions, created with `def` and `lambda`.
dummies = [example_func, lambda: None]
# Either is usable by lookup:
dummies[0]()
dummies[1]()
# They have exactly the same type:
assert(type(dummies[0]) is type(dummies[1]))
实例方法
在Python 3.x中,直接在类中查找实例方法会得到一个普通的函数——没有“未绑定方法”的单独类型。当调用这个函数时,必须显式提供一个实例:
class Example:
def method(self):
pass
instance = Example()
# Explicit syntax for a method call via the class:
Example.method(instance)
# Following all the same patterns as before, that can be separated:
m = Example.method # the function itself
m(instance) # call it
# Again, `type(m)` is the same function type.
在实例上查找实例方法,当然会得到一个绑定方法。
# Calling a method via the instance:
instance.method()
# This, too, is separable:
bound = instance.method
bound()
绑定方法有不同的类型,但提供与函数相同的可调用接口:它们用()
语法调用。
@staticmethod
和@classmethod
这里也没有什么特别意外的:
class Fancy:
@staticmethod
def s(a, b, c):
pass
@classmethod
def c(cls):
pass
f = Fancy()
# For both of these, the result is the same whether lookup
# uses the class or the instance.
assert f.s is Fancy.s
# That assertion will NOT work for the classmethod, because method binding
# creates a new bound method object each time.
# But they can be verified to be functionally identical:
assert type(f.c) is type(Fancy.c)
assert f.c.__code__ is Fancy.c.__code__ # etc.
# As before, the results can be stored and used.
# As one would expect, the `cls` argument is bound for the classmethod,
# while the staticmethod expects all arguments that are listed.
fs = f.s
fs(1, 2, 3)
fc = f.c
fc()
处理参数
尝试从某个数据结构中查找可调用对象(无论是函数、lambda、绑定方法、类等)并调用它的代码,需要能够为调用提供合适的参数。当然,如果每个可用的可调用对象都期望相同数量的参数(具有相同的类型和语义),这将是最容易安排的。在许多情况下,需要通过预填充不会来自查找的公共参数,或者通过包装它们来忽略参数,从而适应这些可调用对象。
def zero():
pass
def one(a):
print('a', a)
def two(a, b):
print('a', a, 'b', b)
funcs = # help!
def dispatch():
a = input('what should be the value of a?')
f = input('which func should be used?')
return funcs[f](a)
忽略参数可以通过编写显式的包装器来实现,或者通过重新设计使得关键字参数被传递(并且让被调用的函数简单地忽略任何多余的**kwargs
内容)。
有关预填充参数的情况,请参见如何在Python中将参数绑定到函数?
例如,我们可以使用lambda进行适配(当参数数量较多时,这会变得很繁琐):
funcs = {
'zero': (lambda a: zero()),
'one': one,
'two': (lambda a: two(a, 'bee'))
}
或者首先重新设计底层函数,使其在这种设置中更易于使用:
from functools import partial
def zero(**kwargs):
pass
def one(a):
print('a', a)
def two(b, a): # this order is more convenient for functools.partial
print('a', a, 'b', b)
funcs = {'zero': zero, 'one': one, 'two': partial(two, 'bee')}
def dispatch():
a = input('what should be the value of a?')
f = input('which func should be used?')
return funcs[f](a=a)
functools.partial
在这里特别有用,因为它避免了由于延迟绑定在lambda中造成的常见陷阱。例如,如果适配器lambda a: two(a, 'bee')
使用了一个变量而不是字面值'bee'
,而这个变量随后发生了变化,那么在使用dispatch
函数时,这个变化会被反映出来(这通常不是我们想要的)。
在Python中,函数被视为一等公民,这意味着你可以用字典来调用它们。比如说,如果有两个函数叫做 foo
和 bar
,而 dispatcher
是一个字典,内容大概是这样的。
dispatcher = {'foo': foo, 'bar': bar}
注意,这个字典里的值是 foo
和 bar
,它们是函数对象,而不是 foo()
和 bar()
(后者是调用函数的结果)。
如果你想调用 foo
,你只需要这样写 dispatcher['foo']()
。
补充一下:如果你想运行存储在列表里的多个函数,你可以尝试这样做。
dispatcher = {'foobar': [foo, bar], 'bazcat': [baz, cat]}
def fire_all(func_list):
for f in func_list:
f()
fire_all(dispatcher['foobar'])