top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration

Facebook Login
Site Registration

Python: How we can make a higher order function in Python?

+2 votes
87 views
Python: How we can make a higher order function in Python?
posted Dec 1, 2014 by Kali Mishra

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Functions and methods are first-class objects in Python, so if you want to pass a function to another function, you can just treat it as any other object.

To bind a function object to a specific context, you can use either nested scopes or 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.

For More :
https://thenewcircle.com/static/bookshelf/python_fundamentals_tutorial/functional_programming.html

answer Mar 30, 2015 by Amit Kumar Pandey
Similar Questions
0 votes

How to read/load the cmake file in python and access its elements. I have a scenario, where i need to load the make file and access its elements. I have tried reading the make file as text file and parsing it,but its not the ideal solution. Please let me know how to load the .mk file and access its elements in python.

+2 votes

Iam on python 2.7 and linux .I need to know if we need to place the modules in a particular or it doesn't matter at all while writing the program.

For Example

import os
import shlex
import subprocess
import time
import sys
import logging
import plaftform.cluster
from util import run

def main():
 """ ---MAIN--- """

if __name__ == '__main__':
 main()

In the above example :

I am guessing may be the python modules like os , shlex etc come first and later the user defined modules like import plaftform.cluster etc

Sorry if my question sounds dump , I was running pep8 and don't see its bothered much about it

Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...