Function in definition vs in call (inside event handler)


#1

In Fast and Furri-ous,
the petMove() function is defined with brackets().
Why aren’t the brackets used in the function call pet.on("spawn", petMove) as well? I realize there is no parameter being passed to it, but… why?

# Benutze einen Ereignisbehandler damit hero und pet beide zur gleichen Zeit laufen.

def petMove():
    pet.moveXY(50, 21)

# Benutze pet.on("spawn", petMove) anstelle von  petMove().
# So werden Dein hero und pet zur gleichen Zeit laufen.
pet.on("spawn", petMove)# Ersetze dies mit pet.on("spawn", petMove)

hero.moveXY(50, 12)

#2

That’s weird, I’ve just thought about that recently as well, It could be something to do with the nature of the function: pet.on(event type, event handler) that you don’t need brackets around the end of a function inside another function, but that is rather odd because in functions inside functions like: hero.findNearest(hero.findByType("archer")) use brackets, Sorry I don’t think I have enough experience with programming to know, @MunkeyShynes is a master coder so is @Chaboi_3000 they might know the reason, although it does work using it with brackets as well. :thinking:


#3

if a function does pass a parameter (unlike petMove) , then it can’t work without the brackets, can it? findByType(“type”) needs a parameter that has to be specified in brackets.
Also: is pet.on a function? It’s introduced as an event handler in this level - so maybe the rule goes like this:

“A function that has no parameter is used without brackets when called inside an event handler”…?

It doesn’t work in this context! Tried it, pet.on("spawn", petMove()) throws a syntax error.


#4

IDK why, with 4 years of python programming(outside codecombat), IDK why the brackets are open. Maybe a bug?


#5

@Chaboi_3000 So is it like this only when the function is called in an event handler, or inside another function, or…?


#6

If you do def onSpawn(event): and then pet.on("spawn", onSpawn(event)) I’m pretty sure that works.


#7

Have you tried it? to me that looks like that cat is biting its own tail


#8

Yeah sorry It’s wrong, I just a vague memory of doing it in a level but I must not have.


#9

Maybe because you don’t need to define anything inside the () so you can just delete it.