Python 中的一等公民
pythonserver side programmingprogramming更新于 2025/10/24 13:32:17
一等公民是支持所有促进其他同类实体的操作的实体。
这些实体通常用于:传递参数、从函数返回值、条件修改和赋值。
在本文中,我们将研究 Python 3.x 或更早版本中一等公民的实现和使用。此外,我们将了解所有实体都被标记为"一等公民"的原因。
这些公民包括变量和函数。
让我们首先熟悉属于"一等公民"的数据类型
- 整数
- 浮点类型
- 复数
- 字符串
上述所有四种类型在 Python 3.x 中都被标记为"一等公民"。或更早。
示例
#整数声明
print("hello world")
int_inp=int(input())
print("This is a First class Citizen of "+str(type(int_inp)))
#浮点类型的声明
float_inp=float(input())
print("This is a First class Citizen of "+str(type(float_inp)))
#复数声明
complex_inp=complex(input())
print("This is a First class Citizen of "+str(type(complex_inp)))
#字符串声明
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 程序
# 被视为对象的函数
def comp_name(text):
return text.isupper()
print(comp_name("TUTORIALSPOINT"))
new_name = comp_name #使用对象引用函数
print(new_name("TutorialsPoint"))
输出
True False
示例
# Python 程序
# 函数作为参数传递给其他函数
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 函数的实现。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

