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

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.

主站蜘蛛池模板: 灵山县| 建瓯市| 杭锦后旗| 瓦房店市| 七台河市| 浦江县| 蓬安县| 祁门县| 开封县| 信宜市| 沅陵县| 白朗县| 肇源县| 乌鲁木齐市| 太仓市| 阿鲁科尔沁旗| 莒南县| 依兰县| 依安县| 改则县| 巩义市| 武清区| 长顺县| 舞阳县| 高唐县| 大化| 广宁县| 昌平区| 卢氏县| 九江县| 曲周县| 平邑县| 隆子县| 漳平市| 赤水市| 尉犁县| 溧水县| 龙口市| 清新县| 连州市| 渭南市|