【问题标题】:Why The function is returning False for None objects [duplicate]为什么该函数为 None 对象返回 False [重复]
【发布时间】:2019-09-04 04:44:59
【问题描述】:

我有一个函数应该检查传入的对象是否被允许。

为什么这个函数对于 None 类型会失败。

def is_valid_object(obj):
    allowed_types = [int, bool, None]
    return type(obj) in allowed_types

工作:

is_valid_object('i am string') 预期 False => 返回 False

is_valid_object(10) 预期 True => 返回 True

is_valid_object(False) 预期 True => 返回 True


为什么会失败:

is_valid_object(None) 预期 True => 返回 False

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    None 不是类型,它是 NoneType 类型的单个值。使用type(None) 访问该类型以将其放入允许的类型列表中:

    allowed_types = [int, bool, type(None)]
    

    在我看来,最好使用obj is None 明确测试None 单例,因为这样的意图更清楚:

    allowed_types = [int, bool]
    return obj is None or type(obj) in allowed_types
    

    考虑使用带有元组第二个参数的isinstance(),而不是使用type(obj) in allowed_types

    def is_valid_object(obj):
        return obj is None or isinstance(obj, (int, bool))
    

    可以简化为:

    def is_valid_object(obj):
        return obj is None or isinstance(obj, int)
    

    因为boolint 的子类。

    演示:

    >>> def is_valid_object(obj):
    ...     return obj is None or isinstance(obj, int)
    ...
    >>> is_valid_object(42)
    True
    >>> is_valid_object(False)
    True
    >>> is_valid_object(None)
    True
    >>> is_valid_object('Hello world!')
    False
    

    【讨论】:

      【解决方案2】:

      intbool 不同,type(None) 不等于None

      print(type(None))
      

      无类型

      解决方法你可以这样做:

      def is_valid_object(obj):
          allowed_types = [int, bool, type(None)]
          return type(obj) in allowed_types
      

      输出

      print(is_valid_object(None))
      

      是的

      【讨论】:

      • type(10) 也不等于 10type(x) == x 仅当 xtype 本身时才为真。
      【解决方案3】:

      None 是一个值,而不是一个类型。 None 类型没有内置名称。使用任一

      def is_valid_object(obj):
          allowed_types = [int, bool, type(None)]
          return type(obj) in allowed_types
      

      或(仅限 Python 2)

      from types import NoneType
      
      def is_valid_object(obj):
          allowed_types = [int, bool, NoneType]
          return type(obj) in allowed_types
      

      无论哪种方式,您的函数都可以通过使用isinstance 而不是类型比较来简化(并且更正确)。

      def is_vali_object(obj):
          return isinstance(obj, (int, bool, type(None)))
      

      (由于None 是其类型的only 值,因此将obj is None 直接检查为Martijn Pieters shows 更容易。)

      【讨论】:

        猜你喜欢
        • 2020-10-17
        • 2020-06-25
        • 1970-01-01
        • 2023-01-01
        • 1970-01-01
        • 2022-11-15
        • 1970-01-01
        • 2013-02-17
        • 2021-10-19
        相关资源
        最近更新 更多