- Python Data Structures and Algorithms
- Benjamin Baka
- 304字
- 2021-07-09 19:44:59
Functions as first class objects
In Python, it is not only data types that are treated as objects. Both functions and classes are what are known as first class objects, allowing them to be manipulated in the same ways as built-in data types. By definition, first class objects are:
- Created at runtime
- Assigned as a variable or in a data structure
- Passed as an argument to a function
- Returned as the result of a function
In Python, the term first class object is a bit of a misnomer since it implies some sort of hierarchy, whereas all Python objects are essentially first class.
To have a look at how this works, let's define a simple function:
def greeting(language):
if language== 'eng':
return 'hello world'
if language == 'fr'
return 'Bonjour le monde'
else: return 'language not supported'
Since user-defined functions are objects, we can do things such as include them in other objects, such as lists:

Functions can also be used as arguments for other functions. For example, we can define the following function:

Here, callf() takes a function as an argument, sets a language variable to 'eng', and then calls the function with the language variable as its argument. We could see how this would be useful if, for example, we wanted to produce a program that returns specific sentences in a variety of languages, perhaps for some sort of natural language application. Here we have a central place to set the language. As well as our greeting function, we could create similar functions that return different sentences. By having one point where we set the language, the rest of the program logic does not have to worry about this. If we want to change the language, we simply change the language variable and we can keep everything else the same.
- 大學(xué)計(jì)算機(jī)基礎(chǔ)(第二版)
- FuelPHP Application Development Blueprints
- CMDB分步構(gòu)建指南
- PyTorch自動(dòng)駕駛視覺(jué)感知算法實(shí)戰(zhàn)
- Koa開(kāi)發(fā):入門(mén)、進(jìn)階與實(shí)戰(zhàn)
- Visual C++串口通信技術(shù)詳解(第2版)
- Flash CS6中文版應(yīng)用教程(第三版)
- Access 2010數(shù)據(jù)庫(kù)應(yīng)用技術(shù)(第2版)
- 青少年信息學(xué)競(jìng)賽
- Mobile Device Exploitation Cookbook
- TMS320LF240x芯片原理、設(shè)計(jì)及應(yīng)用
- C++程序設(shè)計(jì)教程
- Unity Android Game Development by Example Beginner's Guide
- R的極客理想:量化投資篇
- 高效使用Greenplum:入門(mén)、進(jìn)階與數(shù)據(jù)中臺(tái)