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