Python数据不兼容
时间: 2024-06-20 09:02:14 浏览: 8
在 Python 中,数据不兼容(通常称为类型不匹配或类型错误)发生在你尝试对不同类型的值执行某种操作,但这些值的类型不支持那种操作。例如:
1. **算术运算**:当你试图将字符串和整数相加时,会遇到类型错误,因为 `+` 运算符不能直接应用于不同类型的数据。
```python
"5" + 2 # TypeError: can only concatenate str (not "int") to str
```
2. **函数调用**:如果你试图调用一个只接受特定参数类型的函数,而传入了其他类型,也会导致错误。
```python
def print_name(name: str):
print(name)
print_name(123) # TypeError: print_name() missing 1 required positional argument: 'name'
```
3. **列表操作**:试图在列表中插入非可迭代对象也会报错。
```python
[1, 2] + 3 # TypeError: can only concatenate list (not "int") to list
```
4. **对象属性访问**:如果尝试访问不存在的属性或方法,特别是对于不同类型对象时,也会出错。
```python
str_obj = "Hello"
str_obj.append(" World") # AttributeError: 'str' object has no attribute 'append'
```