Python内置内容大揭秘:变量、函数与探索技巧

欢迎来到Python内置内容的奇妙世界!这里就像Python的“百宝箱”,装满了各种开箱即用的工具,让你编程时少走弯路,多写优雅代码。今天,我们就来一场深度探秘之旅!

一、如何查看Python内置内容?

在探索具体内容之前,先学会如何发现宝藏!Python提供了几种查看内置内容的方法:

1. dir(__builtins__) - 你的内置内容地图

# 查看所有内置名称
print("Python内置内容列表:")
for item in dir(__builtins__):
print(item, end=", ")

# 更优雅的显示方式
import pprint
pprint.pprint(dir(__builtins__), compact=True)

2. 使用help()函数 - 内置帮助手册

# 查看特定内置函数的帮助
help(print) # 显示print函数的详细说明

# 查看所有内置函数列表
help('builtins')

3. 区分类型查看

# 分别查看内置函数和异常
builtin_funcs = [name for name in dir(__builtins__)
if not name.startswith('__') and not name[0].islower()]
builtin_exceptions = [name for name in dir(__builtins__)
if name[0].isupper() and name not in ['True', 'False', 'None']]

print("内置函数:", builtin_funcs)
print("内置异常:", builtin_exceptions)

二、内置变量(常量)详解

这些是Python中的“固定标志”,像交通信号灯一样告诉程序该往哪走。

1. TrueFalse - 布尔双雄

# 基本使用
is_python_fun = True
is_java_better = False # 当然不是!

print(f"Python有趣吗?{is_python_fun}")
print(f"1 > 2 吗?{1 > 2}") # 输出: False

# 在条件判断中的使用
if True:
print("这个总是会执行!")

# 注意:True和False首字母大写
true_copy = True # 正确
# true_copy = true # 错误!会报NameError

2. None - 空无一物的艺术家

# None表示没有值
result = None
print(f"结果是:{result}") # 输出: 结果是:None
print(f"result的类型是:{type(result)}") # 输出: <class 'NoneType'>

# 常见用途:函数默认返回值
def find_user(user_id):
if user_id > 100:
return {"name": "小明", "age": 20}
return None # 没找到用户

# 检查是否为None
user = find_user(50)
if user is None: # 推荐使用is而不是==
print("用户不存在!")

# None在布尔上下文中为False
if not None:
print("None就是False!")

3. Ellipsis / ... - 省略号先生

# 两种写法等价
print(Ellipsis) # 输出: Ellipsis
print(...) # 输出: Ellipsis

# 主要用途1:在切片中表示所有维度
import numpy as np
arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print(arr[..., 0]) # 获取所有维度的第一个元素

# 主要用途2:作为占位符
def function_to_be_implemented_later():
... # 先写个省略号,以后再实现

class IncompleteClass:
"""待完善的类"""
...

# 主要用途3:在类型提示中
from typing import Tuple
def get_data() -> Tuple[int, ...]:
return (1, 2, 3, 4, 5)

4. NotImplemented - “我做不到”的优雅表达

class Vector:
def __init__(self, x, y):
self.x = x
self.y = y

def __add__(self, other):
if isinstance(other, Vector):
return Vector(self.x + other.x, self.y + other.y)
return NotImplemented # 告诉Python:我不知道怎么加

v1 = Vector(1, 2)
v2 = Vector(3, 4)

try:
result = v1 + "字符串" # 这会尝试反向操作
except TypeError as e:
print(f"错误信息:{e}")

# 正确使用
v3 = v1 + v2
print(f"向量相加:({v3.x}, {v3.y})") # 输出: (4, 6)

5. __debug__ - 调试小助手

# 默认为True,除非使用-O或-OO选项运行Python
print(f"调试模式:{__debug__}")

# 实际应用:性能优化
if __debug__:
print("这是在调试模式下才会打印的信息")
else:
# 生产环境的优化代码
pass

# 断言语句也依赖__debug__
assert 1 == 1, "数学崩溃了!" # 当__debug__为False时,assert语句会被忽略

三、内置函数精选详解

Python有70多个内置函数,这里精选最常用、最重要的进行详细介绍。

1. 类型相关函数

type() - 身份调查员

# 查看对象类型
print(type(42)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type("Hello")) # <class 'str'>
print(type([1, 2, 3])) # <class 'list'>
print(type({"a": 1})) # <class 'dict'>

# 动态创建类
MyClass = type('MyClass', (), {'x': 10})
obj = MyClass()
print(f"动态创建的类实例属性:{obj.x}") # 输出: 10

isinstance()issubclass() - 家族关系鉴定师

# isinstance检查实例
num = 123
print(isinstance(num, int)) # True
print(isinstance(num, (int, float, str))) # 检查多个类型

# issubclass检查类继承关系
class Animal: pass
class Dog(Animal): pass
class Cat(Animal): pass

print(issubclass(Dog, Animal)) # True
print(issubclass(Dog, Cat)) # False

# 实际应用:类型检查
def process_data(data):
if isinstance(data, list):
return sum(data)
elif isinstance(data, dict):
return list(data.values())
else:
return str(data)

callable() - “可调用吗?”测试器

def say_hello():
print("Hello!")

class Greeter:
def __call__(self):
print("Hi there!")

print(callable(say_hello)) # True
print(callable(42)) # False
print(callable(lambda x: x*2)) # True

greeter = Greeter()
print(callable(greeter)) # True,因为有__call__方法
greeter() # 输出: Hi there!

2. 数学运算函数

abs() - 绝对值使者

print(abs(-10))      # 10
print(abs(3.14)) # 3.14
print(abs(-2.5)) # 2.5

# 复数绝对值
print(abs(3 + 4j)) # 5.0 (计算模长:sqrt(3² + 4²))

# 自定义对象支持abs
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y

def __abs__(self):
return (self.x**2 + self.y**2)**0.5

v = Vector(3, 4)
print(abs(v)) # 5.0

round() - 四舍五入专家

# 基本四舍五入
print(round(3.14159)) # 3
print(round(3.14159, 2)) # 3.14
print(round(3.14159, 3)) # 3.142

# 银行家舍入法(四舍六入五成双)
print(round(2.5)) # 2
print(round(3.5)) # 4
print(round(4.5)) # 4

# 负数的舍入
print(round(-2.5)) # -2
print(round(-3.5)) # -4

divmod() - 商和余数打包员

# 同时获取商和余数
result = divmod(10, 3)
print(result) # (3, 1)
print(f"商:{result[0]}, 余数:{result[1]}")

# 实际应用:时间转换
seconds = 3661
minutes, seconds_remain = divmod(seconds, 60)
hours, minutes_remain = divmod(minutes, 60)
print(f"{seconds}秒 = {hours}小时{minutes_remain}{seconds_remain}秒")

# 浮点数也可以
print(divmod(10.5, 3)) # (3.0, 1.5)

pow() - 幂运算大师

# 基本幂运算
print(pow(2, 3)) # 8,等价于 2**3
print(pow(2, 3, 5)) # 3,计算 (2**3) % 5

# 浮点数幂运算
print(pow(4, 0.5)) # 2.0,平方根
print(pow(27, 1/3)) # 3.0,立方根

# 负数幂运算
print(pow(2, -2)) # 0.25,等价于 1/(2**2)

3. 序列操作函数

len() - 长度测量员

# 各种类型的长度
print(len("Hello")) # 5
print(len([1, 2, 3, 4])) # 4
print(len({"a": 1, "b": 2})) # 2
print(len((1, 2, 3))) # 3
print(len(range(10))) # 10

# 自定义对象支持len
class Playlist:
def __init__(self, songs):
self.songs = songs

def __len__(self):
return len(self.songs)

my_playlist = Playlist(["Song1", "Song2", "Song3"])
print(f"播放列表有{len(my_playlist)}首歌") # 输出: 3

sorted() - 排序魔法师

# 基本排序
numbers = [3, 1, 4, 1, 5, 9, 2]
print(sorted(numbers)) # [1, 1, 2, 3, 4, 5, 9]

# 降序排序
print(sorted(numbers, reverse=True)) # [9, 5, 4, 3, 2, 1, 1]

# 按字符串长度排序
words = ["apple", "banana", "cherry", "date"]
print(sorted(words, key=len)) # ['date', 'apple', 'banana', 'cherry']

# 多级排序
students = [
("Alice", 85, 20),
("Bob", 90, 19),
("Charlie", 85, 21)
]
# 先按分数降序,再按年龄升序
print(sorted(students, key=lambda x: (-x[1], x[2])))

reversed() - 反转大师

# 反转序列
numbers = [1, 2, 3, 4, 5]
print(list(reversed(numbers))) # [5, 4, 3, 2, 1]

# 字符串反转
text = "Python"
print(''.join(reversed(text))) # nohtyP

# 实际应用:回文检查
def is_palindrome(s):
return s == ''.join(reversed(s))

print(is_palindrome("racecar")) # True
print(is_palindrome("python")) # False

# reversed返回的是迭代器,节省内存
large_list = list(range(1_000_000))
reversed_iter = reversed(large_list) # 不占用额外内存

enumerate() - 编号小助手

# 为序列添加索引
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")

# 从指定数字开始编号
for index, fruit in enumerate(fruits, start=1):
print(f"{index}. {fruit}")

# 实际应用:查找元素位置
def find_all_positions(lst, target):
return [i for i, item in enumerate(lst) if item == target]

numbers = [1, 3, 5, 3, 7, 3]
print(find_all_positions(numbers, 3)) # [1, 3, 5]

zip() - 拉链缝合工

# 合并多个序列
names = ["Alice", "Bob", "Charlie"]
scores = [85, 90, 78]
ages = [20, 19, 21]

for name, score, age in zip(names, scores, ages):
print(f"{name}: {score}分, {age}岁")

# 创建字典
score_dict = dict(zip(names, scores))
print(score_dict) # {'Alice': 85, 'Bob': 90, 'Charlie': 78}

# 不等长序列处理
list1 = [1, 2, 3]
list2 = ['a', 'b']
print(list(zip(list1, list2))) # [(1, 'a'), (2, 'b')],以最短的为准

# 解压(unzip)
pairs = [(1, 'a'), (2, 'b'), (3, 'c')]
numbers, letters = zip(*pairs)
print(numbers) # (1, 2, 3)
print(letters) # ('a', 'b', 'c')

filter()map() - 数据转换双子星

# filter: 过滤数据
numbers = range(10)
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(f"偶数:{even_numbers}") # [0, 2, 4, 6, 8]

# 使用None过滤假值
mixed = [0, 1, False, 2, '', 3, None]
truthy_values = list(filter(None, mixed))
print(f"真值:{truthy_values}") # [1, 2, 3]

# map: 转换数据
squares = list(map(lambda x: x**2, range(5)))
print(f"平方数:{squares}") # [0, 1, 4, 9, 16]

# 多个序列的map
list1 = [1, 2, 3]
list2 = [10, 20, 30]
sums = list(map(lambda x, y: x + y, list1, list2))
print(f"对应元素和:{sums}") # [11, 22, 33]

# 实际应用:数据清洗
prices = ["$10.5", "$20.0", "$15.75"]
clean_prices = list(map(lambda x: float(x.replace("$", "")), prices))
print(f"清洗后的价格:{clean_prices}") # [10.5, 20.0, 15.75]

4. 输入输出函数

# 基本输出
print("Hello, World!")

# 多个参数
name = "Alice"
age = 25
print("姓名:", name, "年龄:", age) # 自动用空格分隔

# 自定义分隔符和结束符
print("Python", "is", "fun", sep="-", end="!\n") # Python-is-fun!

# 格式化输出
print(f"姓名:{name},年龄:{age}") # f-string(Python 3.6+)
print("姓名:{},年龄:{}".format(name, age)) # format方法

# 输出到文件
with open("output.txt", "w") as f:
print("保存到文件", file=f)

input() - 用户对话窗口

# 基本输入
name = input("请输入你的名字:")
print(f"你好,{name}!")

# 类型转换
age = int(input("请输入你的年龄:"))
print(f"明年你就{age + 1}岁了!")

# 实际应用:简单计算器
try:
num1 = float(input("请输入第一个数字:"))
num2 = float(input("请输入第二个数字:"))
operation = input("请输入操作符(+, -, *, /):")

if operation == '+':
result = num1 + num2
elif operation == '-':
result = num1 - num2
elif operation == '*':
result = num1 * num2
elif operation == '/':
result = num1 / num2
else:
result = "无效操作符"

print(f"结果:{result}")
except ValueError:
print("输入的不是有效数字!")

5. 迭代和生成函数

range() - 数字序列生成器

# 基本用法
print(list(range(5))) # [0, 1, 2, 3, 4]
print(list(range(2, 6))) # [2, 3, 4, 5]
print(list(range(1, 10, 2))) # [1, 3, 5, 7, 9]

# 倒序
print(list(range(5, 0, -1))) # [5, 4, 3, 2, 1]

# 实际应用:for循环
for i in range(3):
print(f"第{i+1}次循环")

# 与len结合使用
fruits = ["apple", "banana", "cherry"]
for i in range(len(fruits)):
print(f"{i}: {fruits[i]}")

# 大范围数字
big_range = range(1_000_000)
print(big_range[999999]) # 999999,但range对象占用内存很小

iter()next() - 迭代控制双侠

# 手动控制迭代
fruits = ["apple", "banana", "cherry"]
iterator = iter(fruits)

print(next(iterator)) # apple
print(next(iterator)) # banana
print(next(iterator)) # cherry

try:
print(next(iterator)) # 抛出StopIteration
except StopIteration:
print("没有更多元素了!")

# 实际应用:自定义迭代器
class CountDown:
def __init__(self, start):
self.current = start

def __iter__(self):
return self

def __next__(self):
if self.current <= 0:
raise StopIteration
value = self.current
self.current -= 1
return value

for num in CountDown(3):
print(num) # 3, 2, 1

6. 属性操作函数

getattr(), setattr(), hasattr(), delattr() - 属性操作四剑客

class Person:
def __init__(self, name, age):
self.name = name
self.age = age

person = Person("Alice", 25)

# hasattr: 检查属性是否存在
print(hasattr(person, "name")) # True
print(hasattr(person, "height")) # False

# getattr: 获取属性值,可提供默认值
print(getattr(person, "name")) # Alice
print(getattr(person, "height", 170)) # 170(默认值)

# setattr: 设置属性值
setattr(person, "height", 165)
print(person.height) # 165

# 动态添加方法
def say_hello(self):
print(f"Hello, I'm {self.name}")

setattr(Person, "greet", say_hello)
person.greet() # Hello, I'm Alice

# delattr: 删除属性
delattr(person, "height")
# print(person.height) # 现在会报AttributeError

vars()dir() - 对象探秘工具

class Example:
def __init__(self):
self.public = "公开属性"
self._protected = "受保护属性"
self.__private = "私有属性"

def method(self):
pass

obj = Example()

# vars: 返回对象的__dict__属性(实例变量)
print(vars(obj)) # {'public': '公开属性', '_protected': '受保护属性', '_Example__private': '私有属性'}

# dir: 返回对象的所有属性和方法名
print(dir(obj)[:10]) # 显示前10个,包含很多特殊方法

# 实际应用:对象比较
class A:
def __init__(self, x, y):
self.x = x
self.y = y

class B:
def __init__(self, x, y):
self.x = x
self.y = y

a = A(1, 2)
b = B(1, 2)

print(vars(a) == vars(b)) # True,内容相同
print(dir(a) == dir(b)) # False,类型不同,方法不同

7. 编译执行函数

eval()exec() - 动态代码执行者

# eval: 计算表达式的值
result = eval("3 + 4 * 2")
print(f"3 + 4 * 2 = {result}") # 11

# 使用命名空间
x = 10
y = 20
result = eval("x + y", {"x": 5, "y": 10})
print(result) # 15,使用提供的命名空间,而不是全局的x,y

# exec: 执行代码块
code = """
for i in range(3):
print(f"第{i+1}次循环")
"""
exec(code)

# 实际应用:简单计算器
def safe_calculator(expression):
# 限制可用的函数和变量
allowed_names = {"abs": abs, "max": max, "min": min, "round": round}
try:
return eval(expression, {"__builtins__": {}}, allowed_names)
except Exception as e:
return f"错误:{e}"

print(safe_calculator("abs(-5)")) # 5
print(safe_calculator("max(1, 2, 3)")) # 3
# print(safe_calculator("__import__('os').system('ls')")) # 会被阻止

# 重要警告:不要用eval/exec执行不可信的代码!

8. 其他实用函数

open() - 文件操作门户

# 读取文件
with open('example.txt', 'r', encoding='utf-8') as f:
content = f.read()
print(content)

# 写入文件
with open('output.txt', 'w', encoding='utf-8') as f:
f.write("Hello, World!\n")
f.write("这是第二行")

# 追加内容
with open('output.txt', 'a', encoding='utf-8') as f:
f.write("\n这是追加的内容")

# 逐行读取
with open('example.txt', 'r', encoding='utf-8') as f:
for line_number, line in enumerate(f, 1):
print(f"第{line_number}行: {line.strip()}")

sum(), min(), max() - 统计三巨头

# sum: 求和
numbers = [1, 2, 3, 4, 5]
print(sum(numbers)) # 15
print(sum(numbers, 10)) # 25,从10开始加

# min/max: 最小/最大值
print(min(numbers)) # 1
print(max(numbers)) # 5

# 复杂对象的比较
students = [
{"name": "Alice", "score": 85},
{"name": "Bob", "score": 90},
{"name": "Charlie", "score": 78}
]

print(min(students, key=lambda s: s["score"])) # {'name': 'Charlie', 'score': 78}
print(max(students, key=lambda s: s["score"])) # {'name': 'Bob', 'score': 90}

# 多个参数
print(min(1, 2, 3, 4, 5)) # 1
print(max(1.5, 2.3, 0.8)) # 2.3

any()all() - 逻辑判断专家

# any: 任一为真则返回真
print(any([False, False, True])) # True
print(any([0, "", None, []])) # False,所有都为假

# all: 所有为真才返回真
print(all([True, True, False])) # False
print(all([1, "hello", [1, 2]])) # True,所有都为真

# 实际应用:数据验证
def is_valid_user_data(data):
# 检查所有必需字段都存在且非空
required_fields = ["username", "email", "password"]
return all(field in data and data[field] for field in required_fields)

user1 = {"username": "alice", "email": "alice@example.com", "password": "123"}
user2 = {"username": "bob", "email": "", "password": "456"}

print(is_valid_user_data(user1)) # True
print(is_valid_user_data(user2)) # False,email为空

四、总结与最佳实践

经过这次内置内容之旅,你应该已经掌握了Python中最强大的工具集。让我们回顾一下关键点:

使用内置函数的优势:

  1. 性能优越:用C实现,比纯Python代码快得多
  2. 代码简洁:一行内置函数可能替代多行循环
  3. 可靠稳定:经过充分测试,无bug风险
  4. 可读性好:Python开发者都能理解

实用小贴士:

# 1. 链式调用内置函数
data = [5, 2, 8, 1, 9, 3]
result = sum(map(lambda x: x**2, filter(lambda x: x % 2 == 0, data)))
print(f"偶数的平方和:{result}")

# 2. 使用生成器表达式替代map/filter(通常更Pythonic)
result = sum(x**2 for x in data if x % 2 == 0)
print(f"使用生成器表达式:{result}")

# 3. 利用内置函数进行函数式编程
from functools import reduce
product = reduce(lambda x, y: x * y, range(1, 6))
print(f"5的阶乘:{product}") # 120

# 4. 组合使用多个内置函数
text = "Python is AWESOME!"
# 转换为小写,分割单词,反转顺序,再连接
result = ' '.join(reversed(text.lower().split()))
print(result) # "awesome! is python"

最后提醒:

  • 熟悉内置函数是成为Python高手的关键一步
  • 善用help()dir()探索未知领域
  • 记住”Python之禅”:简单优于复杂,内置函数通常是最简单的解决方案

现在,你已经装备了Python内置函数的全套武器库,去编写更优雅、更高效的代码吧!记住,最好的代码往往是那些充分利用语言特性的代码。Happy coding!🐍✨