官术网_书友最值得收藏!

First-class functions

Functional programming is often succinct and expressive. One way to achieve it is by providing functions as arguments and return values for other functions. We'll look at numerous examples of manipulating functions.

For this to work, functions must be first-class objects in the runtime environment. In programming languages such as C, a function is not a runtime object. In Python, however, functions are objects that are created (usually) by the def statements and can be manipulated by other Python functions. We can also create a function as a callable object or by assigning lambda to a variable.

Here's how a function definition creates an object with attributes:

>>> def example(a, b, **kw):
...    return a*b
...
>>> type(example)
<class 'function'>
>>> example.__code__.co_varnames
('a', 'b', 'kw')
>>> example.__code__.co_argcount
2

We've created an object, example, that is of the function() class. This object has numerous attributes. The __code__ object associated with the function object has attributes of its own. The implementation details aren't important. What is important is that functions are first-class objects and can be manipulated just like all other objects. We previously displayed the values of two of the many attributes of a function object.

主站蜘蛛池模板: 洛南县| 合阳县| 绍兴市| 葵青区| 江山市| 蕉岭县| 大理市| 镇原县| 措美县| 大足县| 芜湖县| 彩票| 榆社县| 大荔县| 满洲里市| 哈巴河县| 股票| 皮山县| 漳州市| 伊宁县| 汉川市| 滦平县| 丹棱县| 鲜城| 凉城县| 资兴市| 和林格尔县| 公主岭市| 德阳市| 隆回县| 双峰县| 视频| 邢台市| 凉城县| 宁晋县| 伊吾县| 洛浦县| 高雄县| 和硕县| 白银市| 南郑县|