class Test(object): __init__ = MethodDispatcher('f') @__init__.register(list) def _init_list(self, data): self.data = data @__init__.register(object) def _init_obj(self, datum): self.data = [datum]
def test_register_instance_method(): f = MethodDispatcher('f') class Test(object): @f.register(list) def __init__(self, data): self.data = data @f.register(object) def __init__(self, datum): self.data = [datum] a = Test(3) b = Test([3]) assert a.data == b.data
class HclExpr(object): hcl_type = UnknownType() conn_side = ConnSide.UNKNOWN def __new__(cls, *args): obj = super().__new__(cls) obj.id = ExprIdGen.next_id() ExprTable.add(obj.id, obj) return obj def __ilshift__(self, other): return op_apply('<<=')(self, other) def __add__(self, other): return op_apply('+')(self, other) def __and__(self, other): return op_apply('&')(self, other) def __or__(self, other): return op_apply('|')(self, other) def __xor__(self, other): return op_apply('^')(self, other) def __getattr__(self, item): return op_apply('.')(self, item) def __setitem__(self, key, value): return self[key] __getitem__ = MethodDispatcher('__getitem__') @__getitem__.register(tuple) def _(self, item): if len(item) == 1: return self[item[0]] return self.__getitem__(item[0])[item[1:]] @__getitem__.register(slice) def _(self, item): start = item.start if item.start is not None else 0 if item.step is None: if item.stop is not None: return op_apply('[i:j]')(self, start, item.stop) if item.stop is None: return op_apply('[i:]')(self, start) if item.stop is not None: return op_apply('[i:j:k]')(self, start, item.stop, item.step) if item.stop is None: return op_apply('[i::k]')(self, start, item.step) @__getitem__.register(int) def _(self, item): return op_apply('[i]')(self, item) def to_uint(self): return op_apply('to_uint')(self) def to_sint(self): return op_apply('to_sint')(self) def to_bool(self): return op_apply('to_bool')(self)