有没有办法在 Python 中传递块参数而不先将其定义为函数? [英] Is there any way to pass a block argument in Python without defining it as a function first?

查看:26
本文介绍了有没有办法在 Python 中传递块参数而不先将其定义为函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Ruby 中,块参数的工作方式如下:

in Ruby, a block argument works like this:

def foo_bar (&block)
    block.(4)
end

foo_bar do |x|
    puts x
    puts x * 2
end
=begin
4
8
=end

我在 Python 中看到了以下等价物,但我觉得它很不令人满意,因为它需要定义函数然后才将它作为参数传递:

I've seen the following equivalent in Python, but I find it quite unsatisfactory, because it requires defining the function and only then passing it as an argument:

def foo_bar(block):
    block(4)

def callback(x):
    print(x)
    print(x * 2)

foo_bar(callback) 
'''
4
8
'''

在 Python 中是否有任何替代方法,不需要先定义函数?

is there any alternative to it in Python, that doesn't require the function to be defined first?

推荐答案

不,python 不允许这样的语法糖.它没有匿名函数;它提供的最接近的是 lambdas,但它们有许多限制,即它们只能有一个表达式,即一行代码.

Nope, python doesn't allow such syntax sugar.It doesn't have anonymous functions; the closest it offers is lambdas, but those have a number of restrictions, namely, they can only have one expression, i.e, one "line" of code.

使用def 定义函数是创建可重用代码块的pythonic 方式.

Defining functions with def is the pythonic way to create a reusable block of code.

这篇关于有没有办法在 Python 中传递块参数而不先将其定义为函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆