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

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.

主站蜘蛛池模板: 临汾市| 靖安县| 碌曲县| 来宾市| 昂仁县| 瓮安县| 望谟县| 凭祥市| 伊川县| 临邑县| 绥滨县| 民丰县| 台北县| 綦江县| 信阳市| 海城市| 临夏县| 高安市| 易门县| 泽州县| 潮州市| 四平市| 綦江县| 杭州市| 镇平县| 湖南省| 镇雄县| 化德县| 弥勒县| 阳泉市| 文水县| 东宁县| 枞阳县| 安陆市| 淳化县| 曲麻莱县| 朝阳县| 屏边| 津市市| 云和县| 谷城县|