DEV Community

chanduthedev
chanduthedev

Posted on

1 2

What is first class object in python?

In python, functions are first class objects in python.

Advantages of first class objects:

  • We can treat functions like other normal objects like int, string, list etc
  • We can pass functions as another function arguments, return a function in another function and assign a function to another variable
  • Define a function within a function (Inner functions)
  • This first class object plays a key role in python for decorator design pattern.

Examples:

# Simple function for adding two numbers
def add_num(num1, num2):
    return num1 + num2

# Passing function as a first argument
def add_values(fun, arg1, arg2):
    result = fun(arg1, arg2)
    return result
Enter fullscreen mode Exit fullscreen mode
  • Assigning function name to the variable:
fun = add_num
Enter fullscreen mode Exit fullscreen mode
  • Passing function as a parameter
two_num_sum = add_values(fun, 5, 8))
Enter fullscreen mode Exit fullscreen mode

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️