1.

Functions are higher order objects in Python. What does this statement mean?

Answer»

In programming language context, a first-class object is an entity that can perform all the operations generally available to other scalar data types such as integer, float or string.

As they say, everything in Python is an object and this applies to function (or method) as well.

>>> def testfunction(): print ("hello") >>> type(testfunction) <class 'function'> >>> type(len) <class 'builtin_function_or_method'>

As you can SEE, a built-in function as well as user defined function is an object of function class.

Just as you can have built-in data type object as argument to a function, you can also declare a function with one of its arguments being a function itself. FOLLOWING example illustrates it.

>>> def add(X,y): return x+y >>> def calladd(add, x,y): z=add(x,y) return z >>> calladd(add,5,6) 11

Return value of a function can itself be ANOTHER function. In following example, two functions add() and multiply() are defined. Third function addormultiply() returns one of the first two depending on arguments passed to it.

>>> def add(x,y): return x+y >>> def multiply(x,y): return x*y >>> def addormultiply(x,y,op): if op=='+': return add(x,y) else: if op=='*': return multiply(x,y) >>> addormultiply(5,6,'+') 11 >>> addormultiply(5,6,'*') 30

Thus a function in Python is an object of function class and can be passed to other function as argument or a function can return other function. Hence Python function is a high order object.



Discussion

No Comment Found