How to pass a function as an argument in Python?

Asked

Viewed 114 times

1

I tried it in various ways, using local variables and assigning them the two methods but it didn’t work, does anyone know where I went wrong?

def game(init, loop, frame_rate=60):
    from time import sleep

    stop = False
    time_per_frame = 1 / frame_rate
    frame = 1

    init()

    while True:
        if stop == True:
            break

        sleep(time_per_frame)
        frame += 1

        if frame == frame_rate:
            frame = 1

        loop()

def method1():
    print('Testando', end='')

def method2():
    print('.', end='')

game(method1(), method2())

ERROR:

Traceback (most recent call last):
  File "C:\Users\Lucas\Downloads\teste.py", line 28, in <module>
    game(method1(), method2())
  File "C:\Users\Lucas\Downloads\teste.py", line 8, in game
    init()
TypeError: 'NoneType' object is not callable

1 answer

4


I ran your code and I’ll tell you what’s going on with him. First let the error message

Traceback (most recent call last):
  File "C:\Users\Lucas\Downloads\teste.py", line 28, in <module>
    game(method1(), method2())
  File "C:\Users\Lucas\Downloads\teste.py", line 8, in game
    init()
TypeError: 'NoneType' object is not callable

The message is saying that you are trying to call a value None as if it were a method, that is, the value that game is receiving in the parameter init is a value None and not the function method1. This error occurs because when you run the instruction game(method1(), method2())you is not passing functions method1 and method2 as an argument for the game function but calling them and passing the turn of them to the game function which in this case would be the value None, and when it comes to education init() within the game function the error occurs, because at that moment the value is null.

To pass the function as argument you refer only to its name and do not use parentheses

game(method1, method2)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.