鱼C论坛

 找回密码
 立即注册
查看: 1468|回复: 0

[学习笔记] 位运算-魔法方法

[复制链接]
发表于 2023-3-26 22:02:10 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
>>> # 位运算: << >>> & ^ | ~ 二进制按位运算
>>> # bin()函数将数字转换位二进制,0b开头
>>> print([bin(i) for i in range(10)])
['0b0', '0b1', '0b10', '0b11', '0b100', '0b101', '0b110', '0b111', '0b1000', '0b1001']
>>> # 按位与
>>> print(3 & 4)
0
>>> # 按位或
>>> print(3 | 2)
3
>>> # 按位非,涉及补码
>>> print(~2)
-3
>>> # 按异或
>>> print(3 ^ 2)
1
>>> # 右移,移动位数不能是负数
>>> print(8 >> 2)
2
>>> # 左移,移动位数不能是负数
>>> print(8 << 2)
32
>>> # math 数学函数
>>> import math
>>> print(0.1 + 0.2) == 0.3 + math.ulp(0.3)
0.30000000000000004
False
>>> # __index__(self)用法:让对象作为索引值被访问才会触发
>>> class C:
...         def __index__(self):
...                 print("被拦截了~~")
...                 return 3
...
>>> c = C()
>>> try:
...         print(c[2])
... except TypeError as e:
...         print(e)
... # 'C' object is not subscriptable
...
'C' object is not subscriptable
>>> s = 'fishc'
>>> print(s[c])
被拦截了~~
h
>>> print(s[bin(c)])
被拦截了~~
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string indices must be integers
>>>
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-6-8 12:20

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表