Sobes.tech
Middle

What is a first-class object?

sobes.tech AI

Answer from AI

A first-class object in Python is an entity that has the following properties:

  • Can be assigned to a variable.
  • Can be passed as an argument to a function.
  • Can be returned from a function.
  • Can be stored in a data structure (e.g., list, dictionary).

In Python, functions are first-class objects.

# Function assigned to a variable
def hello():
    print("Hello!")

x = hello
x() # Call the function via the variable

# Function passed as an argument
def apply_func(func):
    func()

apply_func(hello)

# Function returned from another function
def create_greeter():
    def greet():
        print("Greetings!")
    return greet

greeter = create_greeter()
greeter()

# Function stored in a data structure
funcs = [hello, greet] # greet from the previous example
for func in funcs:
    func()