PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, December 10, 2022

[FIXED] How do you pass a function as an argument to another function, but the initial function's arguments change?

 December 10, 2022     function, python, syntax     No comments   

Issue

How can you write a function f that takes another function g as an argument, but where function g has arguments that change dynamically depending on what happens in function f?

A pseudocode example would be:

def function(another_function(parameters)):  # another function passed as an argument, with parameters
    for i in range(10):
        print(another_function(i))

So when i iterates, function f is called with a new argument i every time. How could that be implemented?

I found one can use *args as a parameter, but did not see how it could be implemented.

Cheers


Solution

Let's create a function that takes two parameters. The first parameter is a reference to a function and the other is a parameter to be used by that function

def func1(func, p):
    func(p)

func1(print, 'Hello world!')

So we call func1 with a reference to the built-in print function (doesn't have to be built-in - could be any function that's in scope)

Output:

Hello world!


Answered By - Cobra
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing