# 内置类型

- [异常](#异常)
- [bytearray](#bytearray)
- [bytes](#bytes)
- [字典](#字典)
- [浮点数](#浮点数)
- [整型](#整型)
- [列表](#列表)
- [str](#str)
- [元组](#元组)

## 异常

  所有异常都具有可读性`value`和`errno`属性,而不仅仅是`StopIteration`和`OSError`。

  **原因:**MicroPython经过优化以减小代码大小。

  **解决方法:**只使用`value`上`StopIteration`的异常,合并`errno`异常在`OSError`异常上。不要在其他异常上使用或依赖这些属性。

  示例:

```python
>>> e = Exception(1)
>>> print(e.value)
Traceback (most recent call last):
  File "<stdin>", in <module>
AttributeError: no such attribute
>>> print(e.errno)
Traceback (most recent call last):
  File "<stdin>", in <module>
AttributeError: no such attribute
```

**触发异常**

&emsp;&emsp;示例:

```python
>>> try:#抛出类型异常TypeError
...     raise TypeError
... except TypeError:#捕捉类型异常TypeError
...     raise ValueError
...     
...     
... 
Traceback (most recent call last):
  File "<stdin>", in <module>
ValueError: 
```

**不支持用户定义内置异常的属性 **

&emsp;&emsp;**原因:**MicroPython已针对内存使用进行了高度优化。

&emsp;&emsp;**解决方法:**使用用户定义的异常子类。

&emsp;&emsp;示例:

```python
>>> e = Exception()
>>> e.x = 0#定义内置异常属性失败
Traceback (most recent call last):
  File "<stdin>", in <module>
AttributeError: no such attribute
```

**while循环条件中可能具有不期望的行号的异常**

&emsp;&emsp;**原因**:优化了条件检查以使其在循环主体的末尾进行,并报告该行号。

&emsp;&emsp;示例:

```python
>>> l = ["-foo", "-bar"]
>>> i = 0
>>> while l[i][0] == "-":
...     print("iter")
...     i += 1
...     
...     
... 
iter
iter
Traceback (most recent call last):
  File "<stdin>", in <module>
IndexError: index out of range
```

**Exception .__ init__方法不存在**

&emsp;&emsp;**原因:**MicroPython不完全支持对本机类进行子类化。

&emsp;&emsp;**解决方法:**改用`super()`呼叫:

&emsp;&emsp;示例:

```python
>>> class A(Exception):
...     def __init__(self):
...         Exception.__init__(self)#采用Exception .__ init__方法
...         
...         
... 
>>> a = A()#实例化失败,因为Exception .__ init__方法不存在
Traceback (most recent call last):
  File "<stdin>", in <module>
  File "<stdin>", in __init__
AttributeError: no such attribute

>>> class A(Exception):
...     def __init__(self):
...         super().__init__()#采用`super()`呼叫
...         
...         
... 
>>> a = A()#实例化成功,不报错
```

## bytearray

**bytearray的切片分配不支持RHS**

&emsp;&emsp;示例:

```python
>>> b = bytearray(4)
>>> b[0:1] = [1, 2]#bytearray的切片赋值,引发异常
Traceback (most recent call last):
  File "<stdin>", in <module>
NotImplementedError: array/bytes required on right side
```

## bytes

&emsp;&emsp;bytes对象支持.format()方法

&emsp;&emsp;**原因:**MicroPython努力变得更常规,所以如果[`str`]和[`bytes`]支持`__mod__()`(%运算符),这两个看起来都支持`format()`。bytes对象支持`__mod__ `,但是bytes对象使用`format()`格式,`__mod__ `就编译不出来了

&emsp;&emsp;**解决方法:**如果对CPython兼容性感兴趣,请不要在bytes对象上使用`.format()`。

&emsp;&emsp;示例:

```python
>>> print(b"{}".format(1))#str对象使用format()
b'1'
```

**bytes()具有不能实现的关键字**

&emsp;&emsp;**解决方法:**将编码作为位置参数传递,例如`print(bytes('abc', 'utf-8'))`

&emsp;&emsp;示例:

```python
>>> print(bytes("abc", encoding="utf8"))#将编码作为bytes()位置参数传递,出现异常
Traceback (most recent call last):
  File "<stdin>", in <module>
TypeError: wrong number of arguments
```

**bytes切片步长!= 1时无法实现**

&emsp;&emsp;**原因:**MicroPython已针对内存使用进行了高度优化。

&emsp;&emsp;**解决方法:**对此显着的操作使用显式循环。

&emsp;&emsp;示例:

```python
>>> print(b"123"[0:3:2])
Traceback (most recent call last):
  File "<stdin>", in <module>
NotImplementedError: only slices with step=1 (aka None) are supported
```

## 字典

&emsp;&emsp;字典的键不是集合。

&emsp;&emsp;**原因:**不能实现。

&emsp;&emsp;**解决方法:**在使用集合操作之前,将键显式转换为集合。

&emsp;&emsp;示例:

```python
>>> print({1: 2, 3: 4}.keys() & {1})
Traceback (most recent call last):
  File "<stdin>", in <module>
TypeError: unsupported type for operator
```

## 浮点数

&emsp;&emsp;示例:

```python
>>> print("%.1g" % -9.9)
-10
```

## 整型

&emsp;&emsp;int不能对int派生类型转换

&emsp;&emsp;**解决方法:**除非确实需要,否则避免对内置类型进行子类化。

&emsp;&emsp;示例:

```python
>>> class A(int):
...     __add__ = lambda self, other: A(int(self) + other)
...     
...     
... 
>>> a = A(42)
>>> print(a + a)
Traceback (most recent call last):
  File "<stdin>", in <module>
  File "<stdin>", in <lambda>
TypeError: unsupported type for operator
```

## 列表

**列表删除时步长!= 1不能实施**

&emsp;&emsp;**解决方法:**对此使用循环操作。

&emsp;&emsp;示例:

```python
>>> l = [1, 2, 3, 4]
>>> del l[0:4:2]#列表删除时步长!= 1,失败
Traceback (most recent call last):
  File "<stdin>", in <module>
NotImplementedError:
```

**列表分片存储在可迭代的RHS上不能实现**

&emsp;&emsp;**原因:**RHS被限制为元组或列表

&emsp;&emsp;**解决方法:**在RHS上使用`list(<iter>)`,将可迭代对象转换为列表

&emsp;&emsp;示例:

```python
>>> l = [10, 20]
>>> l[0:1] = range(4)# RHS不能是是可迭代对象
Traceback (most recent call last):
  File "<stdin>", in <module>
TypeError: expected tuple/list
```

**列表存储时步长!= 1不能实现

&emsp;&emsp;**解决方法:**对此操作直接使用循环。

&emsp;&emsp;示例:

```python
>>> l = [1, 2, 3, 4]
>>> l[0:4:2] = [5, 6]#列表存储时步长= 2不能实现
Traceback (most recent call last):
  File "<stdin>", in <module>
NotImplementedError:
```

## str

&emsp;&emsp;不支持开始/结束索引,例如str.endswith(s,start)

&emsp;&emsp;示例:

```python
>>> print("abc".endswith("c", 1))
Traceback (most recent call last):
  File "<stdin>", in <module>
NotImplementedError: start/end indices
```

**不支持属性/子字符串

&emsp;&emsp;示例:

```python
>>> print("{a[0]}".format(a=[1, 2]))
Traceback (most recent call last):
  File "<stdin>", in <module>
NotImplementedError: attributes not supported yet
```

**str(…)不支持关键字参数

&emsp;&emsp;**解决方法:**直接输入编码格式。例如`print(bytes('abc', 'utf-8'))`

&emsp;&emsp;示例:

```python
>>> print(str(b"abc", encoding="utf8"))#str不支持关键字参数
Traceback (most recent call last):
  File "<stdin>", in <module>
TypeError: argument num/types mismatch
```

**不支持str.ljust()和str.rjust()

&emsp;&emsp;**原因:**MicroPython已针对内存使用进行了高度优化。提供简单的解决方法。

&emsp;&emsp;**解决方法:**使用 `"%-10s" % s`代替`s.ljust(10)`,使用`"% 10s" % s`代替`s.rjust(10)`,同样可以使用`"{:<10}".format(s) `或者 `"{:>10}".format(s)`

&emsp;&emsp;示例:

```python
>>> print("abc".ljust(10))#不支持str.ljust()
Traceback (most recent call last):
  File "<stdin>", in <module>
AttributeError: no such attribute
```

**None作为rsplit的第一个参数,例如str.rsplit(None,n)不支持

&emsp;&emsp;示例:

```python
>>> print("a a a".rsplit(None, 1))#不支持str.rsplit(None,n)
Traceback (most recent call last):
  File "<stdin>", in <module>
NotImplementedError: rsplit(None,n)
```

**下标的步长!= 1不能实现

&emsp;&emsp;示例:

```python
>>> print("abcdefghi"[0:9:2])
Traceback (most recent call last):
  File "<stdin>", in <module>
NotImplementedError: only slices with step=1 (aka None) are supported
```

## 元组

&emsp;&emsp;元组的步长!= 1不能实现

&emsp;&emsp;示例:

```python
>>> print((1, 2, 3, 4)[0:4:2])
Traceback (most recent call last):
  File "<stdin>", in <module>
NotImplementedError: only slices with step=1 (aka None) are supported
```