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

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.

主站蜘蛛池模板: 松溪县| 夏津县| 宜良县| 犍为县| 福州市| 西城区| 公安县| 昌黎县| 渭南市| 金溪县| 韩城市| 曲沃县| 六盘水市| 桐庐县| 韶关市| 山阴县| 梅州市| 永善县| 道真| 亳州市| 中江县| 河北区| 武夷山市| 辉县市| 合山市| 沾化县| 岳阳县| 天等县| 和龙市| 江门市| 北票市| 双柏县| 靖边县| 大冶市| 海安县| 无极县| 潼关县| 镇江市| 奉化市| 永仁县| 老河口市|