还有什么更像Python:小羊羔还是没有?

2024-04-20 13:00:49 发布

您现在位置:Python中文网/ 问答频道 /正文

当一个函数接受一个函数参数(或者一个类有一个函数槽)时,有两种方法可供选择:

def foo(..., my_func=None, ...):
    ...
    if my_func:
        my_func(...)
    ...

以及

def foo(..., my_func=(lambda ...: None), ...):
    ...
    my_func(...)
    ...

什么东西更具Pythonic/清晰/可读性?你知道吗

什么是更快的-一个额外的布尔检查或一个平凡的函数调用?你知道吗


Tags: 方法lambda函数noneiffoomydef
1条回答
网友
1楼 · 发布于 2024-04-20 13:00:49

使用时:

>>> def bar():
...     print("Goodbye, World!")
...

我觉得这很有可读性:

>>> def foo(my_func = lambda : None):
...     my_func()
...
>>> foo()
>>> foo(bar)
Goodbye, World!

我觉得这很烦人

>>> def baz(my_func = None):
...     if my_func is not None:
...         my_func()
...
>>> baz()
>>> baz(bar)
Goodbye, World!

在你的生活中尽量不留支票。当你想让它做它擅长的事情时,不要使用任何东西:对着你的脸爆炸。不要要求它安静。不管怎样,如果你使用它,它都会制造恼人的噪音。你知道吗

What is faster - an extra boolean check or a trivial function call?

为什么,以上帝的名义,你在乎吗?你知道吗


作为记录,我认为这是可读的,但过于宽容:

>>> def buz(my_func = lambda **k:None):
...     my_func()
...
>>> buz(bar)
Goodbye, World!

相关问题 更多 >