Most asked top Interview Questions and Answers | Online Test | Mock Test
Education platform for interview prep, online tests, tutorials, and live practice

Build skills with focused learning paths, mock tests, and interview-ready content.

WithoutBook brings subject-wise interview questions, online practice tests, tutorials, and comparison guides into one responsive learning workspace.

Search the library
Prepare Interview

Mock Exams

Make Homepage

Bookmark this page

Subscribe Email Address

Question: How do you make a higher order function in Python?
Answer:

You have two choices: you can use nested scopes or you can use callable objects.

For example, 
suppose you wanted to define linear(a,b) which returns a function f(x) that computes the value a*x+b. Using nested scopes:

def linear(a,b): 
  def result(x):
    return a*x + b
      return result

Or using a callable object: 

class linear: 
  def __init__(self, a, b):
    self.a, self.b = a,b
    def __call__(self, x):
      return self.a * x + self.b

In both cases: 
taxes = linear(0.3,2)
gives a callable object where taxes(10e6) == 0.3 * 10e6 + 2.

 
The callable object approach has the disadvantage that it is a bit slower and results in slightly longer code. However, note that a collection of callables can share their signature via inheritance:

class exponential(linear): 
  # __init__ inherited
  def __call__(self, x):
    return self.a * (x ** self.b)

Object can encapsulate state for several methods: 
class counter:
  value = 0
    def set(self, x): self.value = x
    def up(self): self.value=self.value+1
    def down(self): self.value=self.value-1
    count = counter()
    inc, dec, reset = count.up, count.down, count.set

Here inc(), dec() and reset() act like functions which share the same counting variable.

Save For Revision

Bookmark this item, mark it difficult, or place it in a revision set.

Open My Learning Library
Is it helpful? Yes No

Most helpful rated by users:

©2026 WithoutBook