在将其用作字典元素之前,是否必须正式定义函数?
def my_func():
print 'my_func'
d = {
'function': my_func
}
Run Code Online (Sandbox Code Playgroud)
我宁愿定义内联函数.我只是尝试输入我想要做的事情,但是python语法的空白策略使得在dict中定义内联函数变得非常困难.有没有办法做到这一点?
Mat*_*lor 16
答案似乎是没有办法在python中声明函数内联字典定义.感谢所有花时间做出贡献的人.
你真的需要一本字典,还是只需要getitem访问?
如果是后者,那么使用一个类:
>>> class Dispatch(object):
... def funcA(self, *args):
... print('funcA%r' % (args,))
... def funcB(self, *args):
... print('funcB%r' % (args,))
... def __getitem__(self, name):
... return getattr(self, name)
...
>>> d = Dispatch()
>>>
>>> d['funcA'](1, 2, 3)
funcA(1, 2, 3)
Run Code Online (Sandbox Code Playgroud)
考虑使用 lambda,但请注意 lambda 只能包含一个表达式,并且不能包含语句(请参阅http://docs.python.org/reference/expressions.html#lambda)。
例如
d = { 'func': lambda x: x + 1 }
# call d['func'](2) will return 3
Run Code Online (Sandbox Code Playgroud)
另请注意,在 Python 2 中,print不是函数。所以你必须这样做:
from __future__ import print_function
d = {
'function': print
}
Run Code Online (Sandbox Code Playgroud)
或sys.stdout.write改用
d = {
'function': sys.stdout.write
}
Run Code Online (Sandbox Code Playgroud)
您可以使用装饰器:
func_dict = {}
def register(func):
func_dict[func.__name__] = func
return func
@register
def a_func():
pass
@register
def b_func():
pass
Run Code Online (Sandbox Code Playgroud)
该func_dict最终将使用功能的完整名称映射:
>>> func_dict
{'a_func': <function a_func at 0x000001F6117BC950>, 'b_func': <function b_func at 0x000001F6117BC8C8>}
Run Code Online (Sandbox Code Playgroud)
您可以register根据需要修改使用的密钥。诀窍是我们使用__name__函数的属性来获取适当的字符串。
| 归档时间: |
|
| 查看次数: |
15549 次 |
| 最近记录: |