How to emulate 4-bit integer in Python 3? -
i'd emulate overflow behavior of unsigned 4-bit integers, this:
>>> x, y = int4(10), int4(9) >>> x + y int4(3) >>> x * y int4(10)
inheritance of builtin int
seems work. possible implement int4
class without overriding operator methods __add__
?
no, subclassing int
not automatically re-use type when applying arithmetic it:
>>> class int4(int): ... def __new__(cls, i): ... return super(int4, cls).__new__(cls, & 0xf) ... >>> x, y = int4(10), int4(9) >>> x + y 19 >>> type(x + y) <type 'int'>
you have override __add__
, etc. methods cast int4()
when this.
if ever want support type (e.g. not support converting other numeric types in process), can generate of these:
from functools import wraps class int4(int): def __new__(cls, i): return super(int4, cls).__new__(cls, & 0xf) def add_special_method(cls, name): mname = '__{}__'.format(name) @wraps(getattr(cls, mname)) def convert_to_cls(self, other): bound_original = getattr(super(cls, self), mname) return type(self)(bound_original(other)) setattr(cls, mname, convert_to_cls) m in ('add', 'sub', 'mul', 'floordiv', 'mod', 'pow', 'lshift', 'rshift', 'and', 'xor', 'or'): add_special_method(int4, m) add_special_method(int4, 'r' + m) # reverse operation
this produces methods always return type of self
arithmetic special methods; this'll allow further subclassing of int4
well.
demo:
>>> functools import wraps >>> class int4(int): ... def __new__(cls, i): ... return super(int4, cls).__new__(cls, & 0xf) ... >>> def add_special_method(cls, name): ... mname = '__{}__'.format(name) ... @wraps(getattr(cls, mname)) ... def convert_to_cls(self, other): ... bound_original = getattr(super(cls, self), mname) ... return type(self)(bound_original(other)) ... setattr(cls, mname, convert_to_cls) ... >>> m in ('add', 'sub', 'mul', 'floordiv', 'mod', 'pow', ... 'lshift', 'rshift', 'and', 'xor', 'or'): ... add_special_method(int4, m) ... add_special_method(int4, 'r' + m) # reverse operation ... >>> x, y = int4(10), int4(9) >>> x + y 3 >>> x * y 10
Comments
Post a Comment