Pass X function as parameter to Y function, but only define X parameter within Y

Asked

Viewed 61 times

2

Does anyone know how to make the code below work?

Or some alternative that works, but follows the principle.

def f_numbers(number='no'):
    if number == 'no':
        return 'Você não definiu um número'
    else:
        return 'Seu número: '+number


def func2(func):
    set_number = 2
    print(func(set_number))


def func1():
    func2(f_numbers())


func1()

My original code is different, but I did this little simulation to make it easy to understand.

Updating: Remembering that I can only set the parameter of f_numbers within the function func2, because this value is defined according to a loop for which sits within func2

2 answers

3


TL;DR

If I understand correctly, you have made 2 mistakes, the first is when Voce sends the function f_numbers for func2, instead of sending the object you are sending the execution and the second is in the function f_numbers itself when you concatenate your message with the numbers sent, failed to do the Typecast, try with the code below:

def f_numbers(number='no'):
    if number == 'no':
        return 'Você não definiu um número'
    else:
        return 'Seu número: '+str(number)

def func2(func):
    set_number = 2
    print(func(set_number))

def func1():
    func2(f_numbers)

func1()

Exit:

Seu número: 2

See working on repl.it

  • Something so simple to solve rs. I thought in python, a function sent by parameter was only interpreted as a function if it had been passed in parentheses as well. Really this language is amazing, very simple and practical. @Sidon

1

One way to do this is this::

def f_numbers(number=True):
    if number:
        return 'Seu número: '+ f'{number}'
    else:
        return 'Você não definiu um número'


def func2(f_numbers):
    number = <Aqui você digita um número ou None caso queira um valor nulo>
    print(f_numbers(number))


def func1():
    func2(f_number)


func1()

The output is as follows::

If you enter a number:

$ python3 functions.py
Seu número: 2

If you let None:

$ python3 functions.py
Você não definiu um número
  • Thanks for the contribution. But in this case this alternative does not serve me, because the value of the function f_numbers can only be defined within the function func2

  • @Suel, got it. Well, if no one can answer your question tomorrow I’ll try. See you later :)

  • @Suel, that’s the way you wanted it?

  • Yes, exactly. Your reply along with that of friend @Sidon works as I would like. Thank you very much !

Browser other questions tagged

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