Jak zaimplementować niepodpisane int 32 w C w Pythonie bez zewnętrznych zależności?
Potrzebuję klasy, która zachowałaby wszystkie funkcje Pythonaint
klasy, ale upewnij się, że jej wyniki mieszczą się w 32-bitowych liczbach całkowitych, tak jak w języku programowania C. Typ musi być „trujący” - wykonanie operacji na int i tego typu powinno spowodować zwrócenie tego typu. Jak zasugerowano w jednej z odpowiedzina moje drugie pytanie, Zwykłem używaćnumpy.uint32
w tym celu, ale wydaje się zbyt głupie, aby dodać tak dużą zależność tylko dla pojedynczego, stosunkowo prostego typu. Jak to osiągnąć? Oto moje dotychczasowe próby:
MODULO = 7 # will be 2**32 later on
class u32:
def __init__(self, num = 0, base = None):
print(num)
if base is None:
self.int = int(num) % MODULO
else:
self.int = int(num, base) % MODULO
def __coerce__(self, x):
return None
def __str__(self):
return "<u32 instance at 0x%x, int=%d>" % (id(self), self.int)
def __getattr__(self, x):
r = getattr(self.int, x)
if callable(r):
def f(*args, **kwargs):
ret = r(*args, **kwargs) % MODULO
print("x=%s, args=%s, kwargs=%s, ret=%s" % (x, args, kwargs, ret))
if x not in ['__str__', '__repr__']:
return u32(ret)
return r(*args, **kwargs)
return f
return r
u = u32(4)
print("u/2")
a = u * 2
assert(isinstance(a, u32))
print("\n2/u")
a = 2 * u
assert(isinstance(a, u32))
print("\nu+u")
"""
Traceback (most recent call last):
File "u32.py", line 44, in <module>
a = u + u
File "u32.py", line 18, in f
ret = r(*args, **kwargs) % MODULO
TypeError: unsupported operand type(s) for %: 'NotImplementedType' and 'int'
"""
a = u + u
assert(isinstance(a, u32))