- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
- Python Advanced Tutorial
- Python - Classes/Objects
- Python - Reg Expressions
- Python - CGI Programming
- Python - Database Access
- Python - Networking
- Python - Sending Email
- Python - Multithreading
- Python - XML Processing
- Python - GUI Programming
- Python - Further Extensions
First Class functions in Python
In different programming languages, First Class objects are those objects, which can be handled uniformly. First Class objects can be stored as Data Structures, as some parameters of some other functions, as control structures etc. We can say that a function in Python is First Class Function, if it supports all of the properties of a First Class object.
What are the properties of First Class Functions?
- It is an instance of an Object type
- Functions can be stored as variable
- Pass First Class Function as argument of some other functions
- Return Functions from other function
- Store Functions in lists, sets or some other data structures.
At first we will see how Functions in Python can be used as an object. In Python, a function can be assigned as variable. To assign it as variable, the function will not be called. So parentheses '()' will not be there.
def cube(x): return x*x*x res = cube(5) print(res) my_cube = cube #The my_cube is same as the cube method res = my_cube(5) print(res)
Now we will see how functions can be passed as argument of another functions. Here is the example.
def cube(x): return x*x*x defmy_map(method, argument_list): result = list() for item in argument_list: result.append(method(item)) return result my_list = my_map(cube, [1, 2, 3, 4, 5, 6, 7, 8]) #Pass the function as argument print(my_list)
[1, 8, 27, 64, 125, 216, 343, 512]
Here is the third property of First Class Functions. In this case we will return one function from another function.
defcreate_logger(message): deflog(): print('Log Message: ' + message) return log #Return a function my_logger = create_logger('Hello World') my_logger()
Log Message: Hello World
- Related Articles
- First-Class Citizens in Python
- How do I enumerate functions of a Python class?
- Mathematical Functions in Python - Special Functions and Constants
- Decimal Functions in Python
- Operator Functions in Python
- Time Functions in Python?
- Mathematical Functions in Python?
- Partial Functions in Python?
- Log functions in Python
- Iterator Functions in Python
- Trigonometric Functions in Python
- Statistical Functions in Python
- What are member functions of a class in C#?
- The :first-child Pseudo-class in CSS