Open In App

First Class functions in Python

Last Updated : 25 Nov, 2020
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow


First class objects in a language are handled uniformly throughout. They may be stored in data structures, passed as arguments, or used in control structures. A programming language is said to support first-class functions if it treats functions as first-class objects. Python supports the concept of First Class functions.

Properties of first class functions:

  • A function is an instance of the Object type.
  • You can store the function in a variable.
  • You can pass the function as a parameter to another function.
  • You can return the function from a function.
  • You can store them in data structures such as hash tables, lists, …

Examples illustrating First Class functions in Python

1. Functions are objects: Python functions are first class objects. In the example below, we are assigning function to a variable. This assignment doesn’t call the function. It takes the function object referenced by shout and creates a second name pointing to it, yell.




# Python program to illustrate functions
# can be treated as objects
def shout(text):
    return text.upper()
  
print (shout('Hello'))
  
yell = shout
  
print (yell('Hello'))


Output:

HELLO
HELLO

2. Functions can be passed as arguments to other functions: Because functions are objects we can pass them as arguments to other functions. Functions that can accept other functions as arguments are also called higher-order functions. In the example below, we have created a function greet which takes a function as an argument.




# Python program to illustrate functions
# can be passed as arguments to other functions
def shout(text):
    return text.upper()
  
def whisper(text):
    return text.lower()
  
def greet(func):
    # storing the function in a variable
    greeting = func("""Hi, I am created by a function
                    passed as an argument.""")
    print (greeting) 
  
greet(shout)
greet(whisper)


Output

HI, I AM CREATED BY A FUNCTION PASSED AS AN ARGUMENT.
hi, i am created by a function passed as an argument.

3. Functions can return another function: Because functions are objects we can return a function from another function. In the below example, the create_adder function returns adder function.




# Python program to illustrate functions
# Functions can return another function
  
def create_adder(x):
    def adder(y):
        return x+y
  
    return adder
  
add_15 = create_adder(15)
  
print (add_15(10))


Output:

25


Previous Article
Next Article

Similar Reads

Mathematical Functions in Python | Set 1 (Numeric Functions)
In python a number of mathematical operations can be performed with ease by importing a module named "math" which defines various functions which makes our tasks easier. 1. ceil() :- This function returns the smallest integral value greater than the number. If number is already integer, same number is returned. 2. floor() :- This function returns t
3 min read
Mathematical Functions in Python | Set 2 (Logarithmic and Power Functions)
Numeric functions are discussed in set 1 below Mathematical Functions in Python | Set 1 ( Numeric Functions) Logarithmic and power functions are discussed in this set. 1. exp(a) :- This function returns the value of e raised to the power a (e**a) . 2. log(a, b) :- This function returns the logarithmic value of a with base b. If base is not mentione
3 min read
Mathematical Functions in Python | Set 3 (Trigonometric and Angular Functions)
Some of the mathematical functions are discussed in below set 1 and set 2 Mathematical Functions in Python | Set 1 (Numeric Functions) Mathematical Functions in Python | Set 2 (Logarithmic and Power Functions) Trigonometric and angular functions are discussed in this article. 1. sin() :- This function returns the sine of value passed as argument. T
3 min read
Mathematical Functions in Python | Set 4 (Special Functions and Constants)
Some of the mathematical functions are discussed in below set 1, set 2 and set 3 Mathematical Functions in Python | Set 1 (Numeric Functions) Mathematical Functions in Python | Set 2 (Logarithmic and Power Functions) Mathematical Functions in Python | Set 3 (Trigonometric and Angular Functions) Special Functions and constants are discussed in this
2 min read
Attaching a Decorator to All Functions within a Class in Python
Decorators in Python allow us to add extra features to functions or methods of class without changing their code. Sometimes, we might want to apply a decorator to all methods in a class to ensure they all behave in a certain way. This article will explain how to do this step by step. Applying Decorators to Class MethodsTo apply a decorator to all m
2 min read
Why we write #!/usr/bin/env python on the first line of a Python script?
The shebang line or hashbang line is recognized as the line #!/usr/bin/env python. This helps to point out the location of the interpreter intended for executing a script, especially in Unix-like operating systems. For example, Linux and macOS are Unix-like operating systems whose executable files normally start with a shebang followed by a path to
2 min read
Create Derived Class from Base Class Universally in Python
In object-oriented programming, the concept of inheritance allows us to create a new class, known as the derived class, based on an existing class, referred to as the base class. This facilitates code reusability and structuring. Python provides a versatile way to create derived classes from base classes universally, allowing for flexibility and sc
3 min read
Call a Class Method From another Class in Python
In object-oriented programming, classes play a pivotal role in organizing and structuring code. Python, being an object-oriented language, allows the creation of classes and their methods to facilitate code modularity and reusability. One common scenario in programming is the need to call a method from one class within another class. In this articl
3 min read
Time Functions in Python | Set 1 (time(), ctime(), sleep()...)
Python has defined a module, "time" which allows us to handle various operations regarding time, its conversions and representations, which find its use in various applications in life. The beginning of time started measuring from 1 January, 12:00 am, 1970 and this very time is termed as "epoch" in Python. Operations on Time in Python Python time.t
4 min read
Array in Python | Set 2 (Important Functions)
Array in Python | Set 1 (Introduction and Functions)Array in Python | Set 2Below are some more useful functions provided in Python for arrays: Array Typecode FunctionThis function returns the data type by which the array is initialized. In this example, we are using arr.typecode to find out the data type of array initialization. C/C++ Code # import
3 min read
Bisect Algorithm Functions in Python
The purpose of Bisect algorithm is to find a position in list where an element needs to be inserted to keep the list sorted. Python in its definition provides the bisect algorithms using the module "bisect" which allows keeping the list in sorted order after the insertion of each element. This is essential as this reduces overhead time required to
5 min read
Python | Set 2 (Variables, Expressions, Conditions and Functions)
Introduction to Python has been dealt with in this article. Now, let us begin with learning python. Running your First Code in Python Python programs are not compiled, rather they are interpreted. Now, let us move to writing python code and running it. Please make sure that python is installed on the system you are working on. If it is not installe
3 min read
Python | startswith() and endswith() functions
Python library provides a number of built-in methods, one such being startswith() and endswith() functions which are used in string related operations. Startswith() Syntax: str.startswith(search_string, start, end) Parameters : search_string : The string to be searched. start : start index of the str from where the search_string is to be searched.
2 min read
maketrans() and translate() functions in Python
In the world of programming, seldom there is a need to replace all the words/characters at once in the whole file python offers this functionality using functions translate() and its helper functions maketrans(). Both functions are discussed in this article. maketrans() maketrans() function is used to construct the transition table i.e specify the
3 min read
Difference Between tf.Session() And tf.InteractiveSession() Functions in Python Tensorflow
In this article, we are going to see the differences between tf.Session() and tf.InteractiveSession(). tf.Session() In TensorFlow, the computations are done using graphs. But when a graph is created, the values and computations are not defined. So a session is used to run the graph. The sessions place the graphs on targeted devices and execute them
3 min read
Python bit functions on int (bit_length, to_bytes and from_bytes)
The int type implements the numbers.Integral abstract base class. 1. int.bit_length() Returns the number of bits required to represent an integer in binary, excluding the sign and leading zeros. Code to demonstrate num = 7 print(num.bit_length()) num = -7 print(num.bit_length()) Output: 3 3 2. int.to_bytes(length, byteorder, *, signed=False) Return
1 min read
Difference between input() and raw_input() functions in Python
Developers often have a need to interact with users, either to get data or to provide some sort of result. Most programs today use a dialog box as a way of asking the user to provide some type of input. While Python provides us with two inbuilt functions to read the input from the keyboard. input ( prompt )raw_input ( prompt )input() function Pytho
4 min read
turtle.setpos() and turtle.goto() functions in Python
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support. turtle.setpos() This method is used to move the turtle to an absolute position. This method has Aliases: setpos, setposition, goto. S
1 min read
Why and how are Python functions hashable?
So start with the question i.e. Why and how are Python functions hashable? First, one should know what actually hashable means in Python. So, hashable is a feature of Python objects that tells if the object has a hash value or not. If the object has a hash value then it can be used as a key for a dictionary or as an element in a set. An object is h
2 min read
Executing functions with multiple arguments at a terminal in Python
Commandline arguments are arguments provided by the user at runtime and gets executed by the functions or methods in the program. Python provides multiple ways to deal with these types of arguments. The three most common are: Using sys.argv Using getopt module/li> Using argparse module The Python sys module allows access to command-line argument
4 min read
Python Regex - re.MatchObject.start() and re.MatchObject.end() functions
In this article, we are going to see re.MatchObject.start() and re.MatchObject.end() regex methods. re.MatchObject.start() This method returns the first index of the substring matched by group. Syntax: re.MatchObject.start([group]) Parameter: group: (optional) group defaults to zero (meaning the whole matched substring). Return -1 if group exists b
2 min read
How to store Python functions in a Sqlite table?
SQLite is a relational database system contained in a C library that works over syntax very much similar to SQL. It can be fused with Python with the help of the sqlite3 module. The Python Standard Library sqlite3 was developed by Gerhard Häring. It delivers an SQL interface compliant with the DB-API 2.0 specification described by PEP 249. To use t
3 min read
Understanding Recursive Functions with Python
Recursion is characterized as the process of describing something in terms of itself; in other words, it is the process of naming the function by itself. Recursion is the mechanism of a function calling itself directly or implicitly, and the resulting function is known as a Recursive function. Advantages:Code reusabilityEasily understandableTime co
3 min read
Timing Functions With Decorators - Python
Everything in Python is an object. Functions in Python also object. Hence, like any other object they can be referenced by variables, stored in data structures like dictionary or list, passed as an argument to another function, and returned as a value from another function. In this article, we are going to see the timing function with decorators. D
4 min read
How to Write Spark UDF (User Defined Functions) in Python ?
In this article, we will talk about UDF(User Defined Functions) and how to write these in Python Spark. UDF, basically stands for User Defined Functions. The UDF will allow us to apply the functions directly in the dataframes and SQL databases in python, without making them registering individually. It can also help us to create new columns to our
4 min read
Python - Create or Redefine SQLite Functions
The SQLite does not have functions or stored procedure language like MySQL. We cannot create stored functions or procedures in SQLite. That means the CREATE FUNCTION or CREATE PROCEDURE does not work in SQLite. In SQLite instead of CREATE FUNCTION or CREATE PROCEDURE we have SQLite’s C API which allows us to create our own user-defined functions, o
3 min read
Python Built in Functions
Python is the most popular programming language created by Guido van Rossum in 1991. It is used for system scripting, software development, and web development (server-side). Web applications can be developed on a server using Python. Workflows can be made with Python and other technologies. Database systems are connectable with Python. Files can a
6 min read
Using SQLite Aggregate functions in Python
In this article, we are going to see how to use the aggregate function in SQLite Python. An aggregate function is a database management function that groups the values of numerous rows into a single summary value. Average (i.e., arithmetic mean), sum, max, min, Count are common aggregation functions. SQLite provides us with many aggregate functions
4 min read
Convert Python Functions into PySpark UDF
In this article, we are going to learn how to convert Python functions into Pyspark UDFs We will discuss the process of converting Python functions into PySpark User-Defined Functions (UDFs). PySpark UDFs are a powerful tool for data processing and analysis, as they allow for the use of Python functions within the Spark ecosystem. By converting Pyt
4 min read
Pandas Functions in Python: A Toolkit for Data Analysis
Pandas is one of the most used libraries in Python for data science or data analysis. It can read data from CSV or Excel files, manipulate the data, and generate insights from it. Pandas can also be used to clean data, filter data, and visualize data. Whether you are a beginner or an experienced professional, Pandas functions can help you to save t
6 min read
Article Tags :
Practice Tags :