-
Overview
In functional programming, you work only with pure functions without side effects;
In Python, functions also have side effects rather than just turing an input into an output;
In Python, functions are first-class objects, which means that functions can be passed around and used as arguments, just like any other object.
-
First-class Object
First class object means there are no restrictions on the object’s use, it is the same as any other object.
A first class object is an entity that can be dynamically created, destroyed, passed to a function, returned as a value, and have all the rights as other variables in the programming language have.
The concept of first- and second- class objects was introduced by Christopher Strachey in the 1960s.
简单来讲,first-class object means 别的object有的它都有
-
higher-order function
Functions that can accept other functions as arguments are also called higher-order functions, which are a necessity for the functional programming style;
The classical example for higher-order functions in Python is the built-in map function which takes a function and an iterable and calls the function on each element in the iterable, yielding the results as it goes along;
-
Function in Python
A variable pointing to a function and the funtion itself are two separate concerns;
Functions can be stored in data structures like list, which means a function stored in list can be called without assigning it to a variable first;
Functions can be passed to other functions;
-
Inner function , closure
Python allows function to be defined inside other functions, which called nested functions or inner functions;
The inner function can capture and remember the value of parameters of parent function, such inner functions are called lexical closures (or just closures). A closure remembers the values from its enclosing lexical scope even when the program flow is no longer in that scope;
In practical terms closure means not only can functions return behaviors but they can also pre-configure those behaviors.
The inner function are not defined until the parent function is called.
Object’s can be made callable which means you can use
round parentheses ()on it and pass function call arguments to it. The object’s__call__method make it callable; -
-
References
- Real Python: Primer on Python Decorators
- Dan Bader: Python’s Functions Are First-Class
- StackOverflow: What are “first class” objects
- PEP 318 – Decorators for Functions and Methods
本文探讨了Python中函数的首类对象概念,解释了如何将函数作为参数传递和使用,以及内嵌函数(闭包)的原理。通过实例阐述了高阶函数和闭包如何提升编程灵活性。

被折叠的 条评论
为什么被折叠?



