为什么在调用另一个函数时我不能将函数定义为参数?

时间:2016-08-14 17:27:27

标签: python python-3.x

我知道函数可以在Python中作为参数传递,但我不明白为什么我不能这样做:

>>> def foo(bar): return bar()
... 
>>> foo(def a(): return 'hello')
  File "<stdin>", line 1
    foo(def a(): return 'hello')
          ^
SyntaxError: invalid syntax

当这完全有效时:

>>> def foo(bar): return bar()
... 
>>> def a(): return 'hello'
... 
>>> foo(a)
'hello'

2 个答案:

答案 0 :(得分:4)

def是一个声明。如果您想要匿名函数,请使用lambda表达式。

foo(lambda: 'hello')

答案 1 :(得分:2)

您无法使用lambda。对于函数的对象表示,您可以使用foo(lambda a: 'hello')

var animation = false;

this.executePlan = function(){ // part of object
    var self = this //  part of object

    for (var i = 0; i < this.moves.length; i++){
        var move = this.moves[i];

        if (move.type == "move"){
            var path = new Path({x: self.x, y: self.y}, {x: move.x, y: move.y});

            animation = setInterval(function(){
                console.log("move");
                ctx.clearRect(0, 0, res, res);
                self.draw();
                self.x += path.vector.x;
                self.y += path.vector.y;
                path.vector.s--;
                    if (path.vector.s <= 0){
                        clearInterval(animation);
                    }
                },
            10);
        }
        else if (move.type == "turn"){
            animation = setInterval(function(){ 
                console.log("turn");                    
                if (move.a > 0){
                    self.facing++;
                    move.a--;
                }
                else {
                    self.facing--;
                    move.a++;
                }
                ctx.clearRect(0, 0, res, res);
                ctx.save();
                ctx.translate(self.x, self.y);  
                ctx.rotate(self.facing*Math.PI/180);
                ctx.drawImage(self.img, -self.size/2, -self.size/2, self.size, self.size);
                ctx.restore();
                    if (move.a == 0){
                        clearInterval(animation);
                    }
                },              
            30);
        }
    }
}

或者您可以使用函数的名称,如第二个示例所示。

相关问题