簡體   English   中英

當對象可能是object()實例時檢查類型的正確方法

[英]Proper way to check type when object might be an object() instance

我正在尋找檢查對象類型的正確方法,該對象現在可能是object()的實例:

def _default_json_encoder(obj):
    """ Default encoder, encountered must have to_dict
    method to be serialized.  """
    if hasattr(obj, "to_dict"):
        return obj.to_dict()
    else:
        # object() is used in the base code to be evaluated as True
        if type(obj) == type(object()):
            return {}
        raise TypeError(
            'Object of type %s with value of '
            '%s is not JSON serializable'
            % (type(obj), repr(obj))
        )

if type(obj) == type(object()):
    return {}

不推薦,很不幸

if isinstance(obj, object):
    return {}

將不起作用,因為所有對象都將被評估為True。

那么type(obj) == type(object())是唯一的方法嗎?

如果您的數據結構中確實有object()實例,則可以使用:

type(obj) is object

測試直接實例(類通常是單例)。

但是,我會重新考慮數據結構,並使用另一個原始值(例如True ),專用的單例或專用的類。

專用的單例可能是:

sentinel = object()

然后測試該哨兵:

if obj is sentinel:
    return {}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM