- 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.
- Advanced Quantitative Finance with C++
- Puppet 4 Essentials(Second Edition)
- 從零開始:數字圖像處理的編程基礎與應用
- 復雜軟件設計之道:領域驅動設計全面解析與實戰
- Android項目開發入門教程
- Spring技術內幕:深入解析Spring架構與設計
- Mastering Linux Network Administration
- H5頁面設計:Mugeda版(微課版)
- 智能搜索和推薦系統:原理、算法與應用
- Python機器學習之金融風險管理
- Python大學實用教程
- Backbone.js Testing
- 跟戴銘學iOS編程:理順核心知識點
- PowerDesigner 16 從入門到精通
- Unity Android Game Development by Example Beginner's Guide