阅读MySQL Connector / Python碰见的一段很巧妙的代码”|=“
阅读MySQL Connector / Python碰见的一段很巧妙的代码”|=“
cursor_type = 0
if buffered is True:
cursor_type |= 1
if raw is True:
cursor_type |= 2
if dictionary is True:
cursor_type |= 4
if named_tuple is True:
cursor_type |= 8
if prepared is True:
cursor_type |= 16
types = {
0: CMySQLCursor, # 0
1: CMySQLCursorBuffered,
2: CMySQLCursorRaw,
3: CMySQLCursorBufferedRaw,
4: CMySQLCursorDict,
5: CMySQLCursorBufferedDict,
8: CMySQLCursorNamedTuple,
9: CMySQLCursorBufferedNamedTuple,
16: CMySQLCursorPrepared
}
- 这里的
|=符号表示的是位运算,这里使用了位运算省去了大量无用的If代码 - 这里也可以直接判断哪两个配置项可以同时设置为 True,如果超过了
types中key的最大取值范围,则会报错,所以这里使用位运算,真是省略了大量判断的代码。
[解析] 这里的 |= 相当于 += 即 cursor_type |= 1 相当于 cursor_type = cursor_type | 1,其中 | 为 Python 中的 或运算,|按位或和&按位与计算方式都是转换二进制再计算,不同的是运算规则(一个为真即为真)1|0 = 1 , 1|1 = 1 , 0|0 = 0 , 0|1 = 1.

浙公网安备 33010602011771号