Python 中的一等公民
一等公民是指能夠支援所有促進其他實體的操作的實體。
這些實體通常用於:傳遞引數、從函式返回值、條件修改和值賦值。
在本文中,我們將瞭解 Python 3.x 或更早版本中一等公民的實現和用法。此外,我們還將學習哪些實體被賦予一等公民的標籤。
這些公民包括變數和函式。
讓我們首先熟悉屬於一等公民的資料型別
- 整數
- 浮點數
- 複數
- 字串
上面提到的所有四種類型在 Python 3.x 或更早版本中都被賦予了一等公民的標籤。
示例
#Declaration of an integer
print("hello world")
int_inp=int(input())
print("This is a First class Citizen of "+str(type(int_inp)))
#Declaration of floating type
float_inp=float(input())
print("This is a First class Citizen of "+str(type(float_inp)))
#Declaration of complex numbers
complex_inp=complex(input())
print("This is a First class Citizen of "+str(type(complex_inp)))
#Declaration of Strings
str_inp=input()
print("This is a First class Citizen of "+str(type(str_inp)))輸入
2 23.4 4+7j tutorialspoint
輸出
This is a First class Citizen of <class 'int'> This is a First class Citizen of <class 'float'> This is a First class Citizen of <class 'complex'> This is a First class Citizen of <class 'str'>
現在讓我們看看一些被稱為一等公民的函式
一等物件在 Python 語言中得到統一處理。作為面向物件的語言,每個實體都引用一個預設物件,該物件可以在任何時間點被引用和取消引用。儲存可以使用資料結構或控制結構來完成。
現在我們將看看 Python 是否支援一等函式。因此,當任何語言將函式視為一等物件時,就被認為支援一等函式。
示例
# Python program
# functions being be treated as objects
def comp_name(text):
return text.isupper()
print(comp_name("TUTORIALSPOINT"))
new_name = comp_name #referencing a function with the object
print(new_name("TutorialsPoint"))輸出
True False
示例
# Python program
# functions being passed as arguments to other functions
def new_inp(text):
return text.upper()
def old_inp(text):
return text.lower()
def display(func):
# storing the function in a normal variable
code = func("Love Coding, Learn everything on Tutorials Point")
print (code)
display(new_inp) #directly referenced by passing functions as arguments.
display(old_inp)輸出
LOVE CODING, LEARN EVERYTHING ON TUTORIALS POINT love coding, learn everything on tutorials point
在這裡可以清楚地看到,Python 函式可以使用物件進行引用,也可以作為引數傳遞給另一個函式,這清楚地表明在 Python 中函式是一等公民,並且可以使用物件實體進行引用和取消引用。
結論
在本文中,我們學習了包含在標準 Python 庫中的 max 和 min 函式的實現。
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP