我需要编写一个类来实现32位无符号整数,就像它们在C编程语言中的工作方式一样。我最关心的是二进制移位,但总体而言,我希望我的类能够:
- 具有与
int
相同的接口,并且可以正常与int
一起使用 - 任何涉及到我的
U32
类的操作(int +U32
,U32
+ int等)也应该返回 U32 - 纯Python - 我不想使用NumPy,ctypes等第三方库。
class U32:
"""Emulates 32-bit unsigned int known from C programming language."""
def __init__(self, num=0, base=None):
"""Creates the U32 object.
Args:
num: the integer/string to use as the initial state
base: the base of the integer use if the num given was a string
"""
if base is None:
self.int_ = int(num) % 2**32
else:
self.int_ = int(num, base) % 2**32
def __coerce__(self, ignored):
return None
def __str__(self):
return "<U32 instance at 0x%x, int=%d>" % (id(self), self.int_)
def __getattr__(self, attribute_name):
print("getattr called, attribute_name=%s" % attribute_name)
# you might want to take a look here:
# https://stackoverflow.com/q/19611001/1091116
r = getattr(self.int_, attribute_name)
if callable(r): # return a wrapper if integer's function was requested
def f(*args, **kwargs):
if args and isinstance(args[0], U32):
args = (args[0].int_, ) + args[1:]
ret = r(*args, **kwargs)
if ret is NotImplemented:
return ret
if attribute_name in ['__str__', '__repr__', '__index__']:
return ret
ret %= 2**32
return U32(ret)
return f
return r
print(U32(4) / 2)
print(4 / U32(2))
print(U32(4) / U32(2))
这里是错误信息:
Traceback (most recent call last):
File "u32.py", line 41, in <module>
print(U32(4) / 2)
TypeError: unsupported operand type(s) for /: 'U32' and 'int'
看起来在Python 3中根本没有调用getattr
技巧。为什么会这样?我如何使这个代码在Python 2和3下都能正常工作?
__special__
特殊方法查找也会忽略__getattribute__
和__getattr__
。更新后给你一个替代方案。 - Martijn Pieters