-1

I have the following code:

def print_function(values, test):
    for x in values:
        print('f(', x,')=', test(x), sep='')


def poly(x):
    return 2 * x**2 - 4 * x + 2


print_function([x for x in range(-2, 3)], poly)

I understand what the poly function does. What I don't understand is the test(x)? What does this do and where is the connection to the poly function?

Alex Waygood
  • 6,304
  • 3
  • 24
  • 46
Leona
  • 19
  • 2
  • 1
    Functions are first class member, poly is passed as the argument to test, so when the function calls test it is really calling poly – Robin Gertenbach Oct 03 '21 at 11:38
  • 3
    Does this answer your question? [What are "first class" objects?](https://stackoverflow.com/questions/245192/what-are-first-class-objects) – Robin Gertenbach Oct 03 '21 at 11:40
  • 2
    Besides the above answers, you could try to run here - https://pythontutor.com/ to see the visual running steps. – Daniel Hao Oct 03 '21 at 11:43
  • You could add this line after `for loop` - `print(f' test: {test} & {type(test}} ')` to confirm your understanding – Daniel Hao Oct 03 '21 at 11:48

1 Answers1

2

In python, functions can be stored in other variables and then called as functions themselves.

Example

def myfunction():
        print('hello')
    
myfunction() #prints hello
    
alias_myfunction = myfunction # store function object in other variable
    
alias_myfunction() #prints hello as well

# use id to test if myfunction and alias_myfunction point to same object.
print(id(myfunction) == id(alias_myfunction)) 

Output

hello
hello
True

Both myfunction and alias_myfunction store the reference to the function object

This can be confirmed using id

In this particular case

# values -> [x for x in range(-2, 3)]
# test -> poly
def print_function(values, test):
    for x in values:
        print('f(', x,')=', test(x), sep='') 
        # When test(x) is called, it is essentially calling poly(x)    

def poly(x):
    return 2 * x**2 - 4 * x + 2
    
print_function([x for x in range(-2, 3)], poly)
Balaji
  • 795
  • 1
  • 2
  • 10