我需要编写一个实现32位无符号整数的类,就像它们在C编程语言中一样.我最关心的是二元转换,但我通常希望我的班级:
具有相同的接口,int
具有与工作int
正常
我的U32
类(int + U32
,U32
+ int等)的任何操作也返回U32
是纯python - 我不想使用NumPy,ctypes等.
正如在这个答案中可以找到的,我得到了一个在Python 2下运行的解决方案.最近我尝试在Python 3下运行它并注意到虽然以下测试代码在旧版本的Python下工作正常,但Python 3引发了一个错误:
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 "" % (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: # /sf/ask/17360801/ 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, inprint(U32(4) / 2) TypeError: unsupported operand type(s) for /: 'U32' and 'int'
getattr
在Python 3中看起来根本没有调用这个技巧.为什么会这样?如何在Python 2和3下使用此代码?