Skip to content

1. 类型分类

Python 中的数据类型主要分为以下几类:

1-1. 数值类型

  • int (整数): 如 1, 100, -10
  • float (浮点数): 如 3.14, -0.001, 2.0
  • complex (复数): 如 3+4j

1-2. 字符串类型(str)

  • 使用单引号或双引号表示: 'hello', "world"
  • 支持多行字符串(三引号): '''多行文本''', """多行文本"""

1-3. 序列类型

  • list (列表): 可变序列,如 [1, 2, 3]
  • tuple (元组): 不可变序列,如 (1, 2, 3)
  • range (范围): 表示数字序列,如 range(5)

1-4. 映射类型

  • dict (字典): 键值对的集合,如 {'name': 'Python', 'version': 3.9}

1-5. 集合类型

  • set (集合): 无序不重复元素集合,如 {1, 2, 3}
  • frozenset (冻结集合): 不可变的集合

1-6. 布尔类型(bool)

  • True
  • False

1-7. 空值类型

  • None: 表示空值或空对象

2. 类型检测

Python 提供了多种方式来检测变量的类型:

2-1. 使用 type() 函数

python
x = 10
print(type(x))  # <class 'int'>
y = "Hello"
print(type(y))  # <class 'str'>

2-2. 使用 isinstance() 函数

python
# 基本用法
x = 10
print(isinstance(x, int))     # True
print(isinstance(x, (int, float)))  # True,可以同时检查多个类型

# 继承关系检查
class Animal:
    pass

class Dog(Animal):
    pass

dog = Dog()
print(isinstance(dog, Dog))    # True
print(isinstance(dog, Animal)) # True

2-3. 使用 issubclass() 函数

python
# 检查类的继承关系
class Animal:
    pass

class Dog(Animal):
    pass

print(issubclass(Dog, Animal))    # True
print(issubclass(Animal, object)) # True,所有类都继承自 object

2-4. 使用 hasattr() 函数

python
# 检查对象是否具有特定属性
class Person:
    def __init__(self, name):
        self.name = name

person = Person("Alice")
print(hasattr(person, 'name'))    # True
print(hasattr(person, 'age'))     # False

2-5. 类型检测的最佳实践

python
def process_data(data):
    # 使用 isinstance 进行类型检查
    if isinstance(data, (int, float)):
        return data * 2
    elif isinstance(data, str):
        return data.upper()
    elif isinstance(data, list):
        return [item * 2 for item in data]
    else:
        raise TypeError("不支持的数据类型")

# 使用示例
print(process_data(10))      # 20
print(process_data("hello")) # "HELLO"
print(process_data([1, 2, 3])) # [2, 4, 6]

2-6. 注意事项

  1. type()isinstance() 的区别:
    • type() 返回对象的精确类型
    • isinstance() 会考虑继承关系,更灵活
  2. 推荐使用 isinstance() 而不是 type(),因为:
    • 支持类型元组检查
    • 考虑继承关系
    • 更符合 Python 的面向对象设计理念
  3. 类型检查应该在必要时使用,过度使用可能会降低代码的灵活性
  4. 在 Python 3.10+ 中,可以使用 match 语句进行类型匹配:
python
def process_value(value):
    match value:
        case int():
            return "整数"
        case str():
            return "字符串"
        case list():
            return "列表"
        case _:
            return "其他类型"

3. 类型转换

Python 提供了多种内置函数来进行类型转换:

3-1. 数值类型转换

python
# 转换为整数
int(3.14)      # 3
int("123")     # 123
int(True)      # 1

# 转换为浮点数
float(3)       # 3.0
float("3.14")  # 3.14
float(True)    # 1.0

# 转换为复数
complex(3)     # 3+0j
complex(3, 4)  # 3+4j

3-2. 字符串转换

python
# 转换为字符串
str(123)       # "123"
str(3.14)      # "3.14"
str(True)      # "True"
str([1, 2, 3]) # "[1, 2, 3]"

3-3. 序列类型转换

python
# 转换为列表
list("Python")     # ['P', 'y', 't', 'h', 'o', 'n']
list((1, 2, 3))    # [1, 2, 3]
list({1, 2, 3})    # [1, 2, 3]

# 转换为元组
tuple([1, 2, 3])   # (1, 2, 3)
tuple("Python")     # ('P', 'y', 't', 'h', 'o', 'n')

# 转换为集合
set([1, 2, 2, 3])  # {1, 2, 3}
set("Python")       # {'P', 'y', 't', 'h', 'o', 'n'}

3-4. 布尔类型转换

python
# 转换为布尔值
bool(0)        # False
bool(1)        # True
bool("")       # False
bool(" ")      # True
bool([])       # False
bool([1])      # True
bool(None)     # False

3-5. 注意事项

  1. 不是所有类型之间都可以相互转换
  2. 转换可能会引发异常,建议使用 try-except 处理
  3. 某些转换可能会损失精度(如 float 转 int)
  4. 字符串转数值时,字符串必须符合数值格式

3-6. 类型转换的最佳实践

python
# 安全的类型转换示例
def safe_int_convert(value):
    try:
        return int(value)
    except (ValueError, TypeError):
        return None

# 使用示例
result1 = safe_int_convert("123")  # 123
result2 = safe_int_convert("abc")  # None

4. 关键字

Python 的关键字是预定义的标识符,用于表示特定的语法结构。以下是 Python 中的所有关键字:

python
False       await       else        import      pass
None        break       except      in          raise
True        class       finally     is          return
and         continue    for         lambda      try
as          def         from        nonlocal    while
assert      del         global      not         with
async       elif        if          or          yield

TIP

关键字不能用作变量名、函数名、类名等标识符。