Python 内置函数

PythonBeginner
立即练习

介绍

欢迎来到关于 Python 内置函数的实验。Python 解释器提供了一套丰富的函数和类型,它们始终可用,无需任何导入。这些函数是执行常见任务的基本构建块,涵盖了从数据操作到输入/输出操作的各个方面。

在这个实验中,你将亲手实践一些最核心的内置函数,它们被分成了逻辑组。实验结束时,你将熟练掌握如何使用这些函数来编写更高效、更具可读性的 Python 代码。

数据类型转换与检查

在这一步,你将学习如何在不同数据类型之间进行转换,并使用 int(), str(), list(), dict(), type(), 和 isinstance() 等函数来检查对象。这些是处理 Python 中数据的基本操作。

注意: 如果你不熟悉使用 WebIDE(类似 VS Code),请先在 这个 Lab 学习。

首先,从左侧的文件浏览器中打开文件 step1_conversion.py。我们将在该文件中编写代码。

将以下代码添加到 step1_conversion.py。此代码演示了如何将字符串转换为整数,将元组(tuple)转换为列表(list),以及将一对(pair)的列表转换为字典(dictionary)。它还展示了如何检查对象的类型。

## step1_conversion.py

## int(): 从数字或字符串返回一个整数对象。
num_str = "123"
num_int = int(num_str)
print(f"String '{num_str}' as integer: {num_int}")

## str(): 返回对象的字符串版本。
int_val = 456
str_val = str(int_val)
print(f"Integer {int_val} as string: '{str_val}'")

## list(): 从可迭代对象(iterable)创建一个新的列表。
my_tuple = ('a', 'b', 'c')
my_list = list(my_tuple)
print(f"Tuple {my_tuple} as list: {my_list}")

## dict(): 创建一个新的字典。
my_pairs = [('x', 1), ('y', 2)]
my_dict = dict(my_pairs)
print(f"List of pairs {my_pairs} as dict: {my_dict}")

## type(): 返回一个对象的类型。
print(f"Type of num_int: {type(num_int)}")

## isinstance(): 如果对象是某个类的实例,则返回 True。
is_list = isinstance(my_list, list)
print(f"Is my_list an instance of list? {is_list}")

现在,保存文件并从终端运行它。

python3 step1_conversion.py

你应该会看到以下输出,这证实了数据类型转换和检查已成功完成。

String '123' as integer: 123
Integer 456 as string: '456'
Tuple ('a', 'b', 'c') as list: ['a', 'b', 'c']
List of pairs [('x', 1), ('y', 2)] as dict: {'x': 1, 'y': 2}
Type of num_int: <class 'int'>
Is my_list an instance of list? True

数学和数值运算

在这一步,你将学习使用内置函数执行常见的数学计算。我们将介绍 abs(), sum(), min(), max(), round(), 和 pow()。

从文件浏览器中打开文件 step2_math.py。

将以下代码添加到 step2_math.py 中。此脚本演示了如何将各种数学函数应用于数字和数字列表。

## step2_math.py

numbers = [5, -10, 15, -2, 8]

## abs(): 返回一个数的绝对值。
print(f"Absolute value of -10: {abs(-10)}")

## sum(): 计算可迭代对象中所有元素的和。
print(f"Sum of numbers {numbers}: {sum(numbers)}")

## min(): 返回可迭代对象中最小的元素。
print(f"Minimum of numbers: {min(numbers)}")

## max(): 返回可迭代对象中最大的元素。
print(f"Maximum of numbers: {max(numbers)}")

## round(): 将数字四舍五入到指定的精度。
pi_approx = 3.14159
print(f"Rounding {pi_approx} to 2 decimal places: {round(pi_approx, 2)}")

## pow(): 返回 base 的 exp 次方。
print(f"2 to the power of 3: {pow(2, 3)}")

保存文件并在终端中执行它。

python3 step2_math.py

输出应该显示每次数学运算的结果。

Absolute value of -10: 10
Sum of numbers [5, -10, 15, -2, 8]: 16
Minimum of numbers: -10
Maximum of numbers: 15
Rounding 3.14159 to 2 decimal places: 3.14
2 to the power of 3: 8

处理序列和可迭代对象

在这一步,你将学习如何操作和处理列表(list)和元组(tuple)等序列。我们将介绍 len(), sorted(), reversed(), enumerate(), map(), filter(), 和 zip()。许多这些函数返回迭代器(iterators),它们是高效、节省内存的对象。

打开文件 step3_sequences.py。

将以下代码添加到 step3_sequences.py 中。此脚本将演示如何获取列表的长度、对其排序、反转,以及如何使用 map、filter 和 zip 执行更复杂的转换。

## step3_sequences.py

my_list = [3, 1, 4, 1, 5, 9]
print(f"Original list: {my_list}")

## len(): 返回对象的长度(项的数量)。
print(f"Length of the list: {len(my_list)}")

## sorted(): 从可迭代对象的项中返回一个新的已排序列表。
print(f"Sorted list: {sorted(my_list)}")

## reversed(): 返回一个反向迭代器。我们将其转换为列表以便打印。
print(f"Reversed list: {list(reversed(my_list))}")

## enumerate(): 返回一个枚举对象(索引、值对的迭代器)。
print(f"Enumerated list: {list(enumerate(my_list))}")

## map(): 返回一个迭代器,它将一个函数应用于可迭代对象的每个项。
squared_numbers = map(lambda x: x*x, my_list)
print(f"Squared numbers (map): {list(squared_numbers)}")

## filter(): 从可迭代对象中构造一个迭代器,该迭代器的函数返回 true。
even_numbers = filter(lambda x: x % 2 == 0, my_list)
print(f"Even numbers (filter): {list(even_numbers)}")

## zip(): 并行迭代多个可迭代对象。
list_a = ['a', 'b', 'c']
list_b = [1, 2, 3]
zipped = zip(list_a, list_b)
print(f"Zipped lists: {list(zipped)}")

保存文件并运行它。

python3 step3_sequences.py

你将看到各种序列操作的输出。请注意 reversed、map、filter 和 zip 等函数如何返回迭代器,我们使用 list() 将它们转换为列表以显示其内容。

Original list: [3, 1, 4, 1, 5, 9]
Length of the list: 6
Sorted list: [1, 1, 3, 4, 5, 9]
Reversed list: [9, 5, 1, 4, 1, 3]
Enumerated list: [(0, 3), (1, 1), (2, 4), (3, 1), (4, 5), (5, 9)]
Squared numbers (map): [9, 1, 16, 1, 25, 81]
Even numbers (filter): [4]
Zipped lists: [('a', 1), ('b', 2), ('c', 3)]

输入输出和对象表示

在这一步,你将学习如何处理基本的输入/输出(Input/Output, I/O)操作,以及如何控制对象如何表示为字符串。我们将重点关注 print(), open(), repr(), 和 format()。我们也会简要提及 input()。

打开文件 step4_io.py。

input() 函数从控制台读取一行,将其转换为字符串,然后返回。例如:name = input("Enter your name: ")。为了避免暂停执行,我们不会在脚本中使用它,但这是一个你需要了解的关键函数。

现在,将以下代码添加到 step4_io.py 中。此脚本将写入文件、从文件中读取内容,并演示表示和格式化对象为字符串的不同方法。

## step4_io.py
import datetime

## open(): 打开一个文件并返回一个相应的文件对象。
## 我们使用 'with' 语句来确保文件被自动关闭。
file_path = "/home/labex/project/my_file.txt"
with open(file_path, "w") as f:
    f.write("Hello, LabEx!\n")
    f.write("This is a test file.")
print(f"Successfully wrote to {file_path}")

## 从文件中读取
with open(file_path, "r") as f:
    content = f.read()
    print("--- File Content ---")
    print(content)
    print("--------------------")

## repr(): 返回一个包含对象的可打印的、无歧义的表示的字符串。
now = datetime.datetime(2023, 10, 27, 10, 30, 0)
print(f"str(now): {str(now)}")
print(f"repr(now): {repr(now)}")

## format(): 将一个值转换为“格式化”的表示。
formatted_string = format(123.4567, ".2f")
print(f"Formatted number (123.4567 to .2f): {formatted_string}")

保存文件并在终端中运行它。

python3 step4_io.py

脚本将创建并写入 my_file.txt,然后将其读回并打印内容。它还展示了 datetime 对象中 str() 和 repr() 之间的区别,并演示了数字格式化。

Successfully wrote to /home/labex/project/my_file.txt
--- File Content ---
Hello, LabEx!
This is a test file.
--------------------
str(now): 2023-10-27 10:30:00
repr(now): datetime.datetime(2023, 10, 27, 10, 30)
Formatted number (123.4567 to .2f): 123.46

对象内省与元编程

在最后这一步,你将探索用于与对象属性和命名空间(namespaces)交互的高级函数。这通常被称为内省(introspection)或反射(reflection)。我们将使用 getattr(), hasattr(), setattr(), dir(), globals(), 和 locals()。

打开文件 step5_introspection.py。

我们将定义一个简单的类(class),然后使用内省函数来动态检查和修改它的实例。将以下代码添加到 step5_introspection.py 中。

## step5_introspection.py

class Person:
    species = "Homo sapiens"
    def __init__(self, name, age):
        self.name = name
        self.age = age

p = Person("Alice", 30)

## hasattr(): 如果对象具有指定的属性,则返回 True。
print(f"Does person have 'name' attribute? {hasattr(p, 'name')}")
print(f"Does person have 'height' attribute? {hasattr(p, 'height')}")

## setattr(): 它是 getattr() 的对应函数。它设置对象上的一个属性。
print("Setting attribute 'height' to 175...")
setattr(p, 'height', 175)
print(f"Does person have 'height' attribute now? {hasattr(p, 'height')}")

## getattr(): 返回对象指定属性的值。
print(f"Person's name: {getattr(p, 'name')}")
print(f"Person's height: {getattr(p, 'height')}")

## dir(): 返回当前局部作用域或对象属性中的名称列表。
## 我们检查 'height' 是否现在在属性列表中。
print(f"Is 'height' in dir(p)? {'height' in dir(p)}")

## globals(): 返回当前全局符号表(symbol table)的字典。
## 我们将检查我们的 'Person' 类是否在 globals 中。
print(f"Is 'Person' in globals? {'Person' in globals().keys()}")

## locals(): 返回当前局部符号表的字典。
def a_func():
    x = 10
    print(f"Is 'x' in locals()? {'x' in locals().keys()}")

a_func()

保存文件并运行它。

python3 step5_introspection.py

输出演示了你如何使用字符串名称动态地检查、设置和获取对象的属性。它还展示了如何检查对象的属性以及全局和局部作用域中可用的变量。

Does person have 'name' attribute? True
Does person have 'height' attribute? False
Setting attribute 'height' to 175...
Does person have 'height' attribute now? True
Person's name: Alice
Person's height: 175
Is 'height' in dir(p)? True
Is 'Person' in globals? True
Is 'x' in locals()? True

总结

恭喜你完成了本次实验(Lab)!你已经获得了使用 Python 各种基本内置函数(built-in functions)的实践经验。

在本次实验中,你学习了如何:

  • 在数据类型之间进行转换并检查对象(int, str, type, isinstance)。
  • 执行常见的数学运算(abs, sum, min, max, round)。
  • 操作和处理序列(sequences)和可迭代对象(iterables)(len, sorted, map, filter, zip)。
  • 处理基本的文件输入/输出(I/O)和对象的字符串表示(open, repr, format)。
  • 检查和动态修改对象及命名空间(hasattr, getattr, setattr, dir)。

这些函数是日常 Python 编程的基础。掌握它们将显著提高你的编码效率和代码可读性。请继续探索其他内置函数,并在你自己的项目中练习使用它们。