从函数对象执行函数(Execute a function from a function object)

编程入门 行业动态 更新时间:2024-10-10 07:31:24
函数对象执行函数(Execute a function from a function object)

在所有示例中, a是:

>>> def a(): ... print "aaaaaaa"

我从另一段代码传递了一个函数对象,我需要执行该函数。

当我说“功能对象”时,我指的是这样一个对象:

>>> type(a) <type 'function'>

看看这个:

>>> def function(f): ... print "start" ... f ... print "end" >>> function(a) start end

如果function()正在执行它传递的函数,则输出中间会有一个aaaaaaa (从a()返回,这是传递给它的函数)

那么如何在传递函数对象时执行函数呢?

(对不起,如果不是很清楚,我也会混淆自己......)

In all of the examples, a is :

>>> def a(): ... print "aaaaaaa"

I have been passed a function object from another piece of code, and I need to execute that function.

When I say "function object", I mean an object like this:

>>> type(a) <type 'function'>

Have a look at this:

>>> def function(f): ... print "start" ... f ... print "end" >>> function(a) start end

If function() was executing the function it was passed, the output would have an aaaaaaa in the middle of it (returned from a(), which was the function passed to it)

So how can I execute a function when passed the function object?

(Sorry if this isn't very clear, I'm confusing myself as well...)

最满意答案

只需使用函数调用operator ()调用它:

f()

这就是你在定义之后调用它的方式。 全局名称指向与本地名称f相同的函数对象,因此您需要执行相同的操作来调用它们。

Just call it using the function call operator ():

f()

This is how you would have called a after defining it. The global name a points to the same function object as the local name f, so you need to do the same thing to call them.

更多推荐

本文发布于:2023-07-27 15:19:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1292354.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   对象   Execute   function   object

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!