这本词典是如何在simpleubjson中使用python编码的?

2024-03-29 11:15:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道这是如何工作的,我写了一个简单的二进制导出器类似格式的json到simpleubjson不一样,但我的代码比较慢,而simpleubjson比较快,我注意到simpleubjson使用一个接受类型作为键的字典,你能指导我它是如何工作的吗?你知道吗

调度={}

def __init__(self, default=None):
    self._default = default or self.default

def default(self, obj):
    raise EncodeError('unable to encode %r' % obj)

def encode_next(self, obj):
    tobj = type(obj)
    if tobj in self.dispatch:
        res = self.dispatch[tobj](self, obj)
    else:
        return self.encode_next(self._default(obj))
    if isinstance(res, bytes):
        return res
    return bytes().join(res)

def encode_noop(self, obj):
    return NOOP
dispatch[type(NOOP_SENTINEL)] = encode_noop

def encode_none(self, obj):
    return NULL
dispatch[type(None)] = encode_none

def encode_bool(self, obj):
    return TRUE if obj else FALSE
dispatch[bool] = encode_bool

def encode_int(self, obj):
    if (-2 ** 7) <= obj <= (2 ** 7 - 1):
        return INT8 + CHARS[obj % 256]
    elif (-2 ** 15) <= obj <= (2 ** 15 - 1):
        return INT16 + pack('>h', obj)
    elif (-2 ** 31) <= obj <= (2 ** 31 - 1):
        return INT32 + pack('>i', obj)
    elif (-2 ** 63) <= obj <= (2 ** 63 - 1):
        return INT64 + pack('>q', obj)
    else:
        return self.encode_decimal(Decimal(obj))
dispatch[int] = encode_int
dispatch[long] = encode_int

Tags: selfobjdefaultreturnifdeftyperes
1条回答
网友
1楼 · 发布于 2024-03-29 11:15:24

这是因为它是一个字典的功能,为每一种类型,它编码。这提供了O(1)查找用于编码类型的函数,而O(n)查找用于检查每个类型的if/elseif语句。你知道吗

提供更多信息的链接:

Why store a function inside a python dictionary?

Dictionary of Methods/Functions (Python recipe)

相关问题 更多 >