First-Class Functions

Functions as objects

Interview Relevant: Python fundamentals

First-Class Functions

Functions are objects in Python.

Code Examples

Functions as first-class objects.

python
1def greet(name):
2    return f"Hello, {name}!"
3
4# Assign to variable
5say_hello = greet
6say_hello("Alice")  # Hello, Alice!
7
8# Store in data structures
9funcs = [len, str, int]
10for f in funcs:
11    print(f(42))
12
13# Function attributes
14greet.__name__       # 'greet'
15greet.__doc__        # docstring
16greet.__annotations__  # type hints
17
18# Define attributes
19def counter():
20    counter.count += 1
21    return counter.count
22counter.count = 0
23
24counter()  # 1
25counter()  # 2

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In