Python`None`传递给类型转换函数 [英] Python `None` passed into type-conversion functions

查看:686
本文介绍了Python`None`传递给类型转换函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

None类型的设计决策传递给类型转换函数的原理是什么?

What is the rationale for the design decision for None type being passed into type-conversion functions?

  • bool(None)返回False-这很有意义

str(None)返回'None',这不行-如下所示,返回空字符串将是更好的选择

str(None) returns 'None' which is not okay - Returning an empty string would be a better choice as below

>>> bool(None)
False
>>> bool(str(None))     #Returning empty string will make it consistent by returning False
True
>>> bool('')
False

  • list(None)dict(None)tuple(None)int(None)float(None)返回类型错误-从中返回[]{}()0的错误和0.0这将是显而易见的,并且在许多现实生活中会很有用,以避免手动处理.

  • And list(None), dict(None), tuple(None), int(None), float(None) return Type errors - From which if they return [], {}, (), 0 and 0.0 it would have been a obvious and will be useful in many real life scenarios to avoid manual handling.

    如果有人能解释一下促使Guido采取其他行动的动机,我们将不胜感激.

    It's appreciated If someone could explain what might have motivated Guido to go the other way around.

    PS:这是由以下问题引起的: Python:最惯用的方式将None转换为空字符串?.大多数答案都是if-else方法,在现实生活中,用空字符串,list,dict或0转换/覆盖None是很常见的.

    PS : This arose from this question Python: most idiomatic way to convert None to empty string?. Most of the answers are of if-else approaches where as in real life converting/overriding None by empty string, list, dict or 0 would be common.

    推荐答案

    None仍然是一个对象.它不是一个空值,它只是一个 sentinel ,用于在您拥有的任何地方生产或使用一个对象,但您确实想将其保留为空.

    None is still an object. It is not an empty value, it is merely a sentinel to use anywhere you have to produce or use an object but you really wanted to leave it empty.

    函数调用不需要参数,调用没有参数的东西完全有效.因此,传入None没有任何意义,因为这将是一个参数,而不是零.

    Function calls don't require an argument, calling something with no arguments is perfectly valid. As such there is no point in passing in None, as that would be one argument, not zero.

    然后要使用类型函数创建空"对象,只需将参数列表保留为空:

    To create 'empty' objects using the type functions then, just leave the argument list empty:

    >>> list()
    []
    >>> tuple()
    ()
    >>> str()
    ''
    

    bool()为您提供传入的参数的布尔类型.您可以在不使用参数的情况下调用它:

    bool() gives you the boolean type of the argument you passed in. You can call it without an argument:

    >>> bool()
    False
    

    ,但是如果您传入None,它将确定该对象的真值.对于None,该值为False. str(None)生成字符串'None',该字符串不为空,因此在传递给bool()时为True.请参见 真值测试部分.

    but if you pass in None, it'll determine the truth value of that object. For None that value is False. str(None) produces the string 'None', which is not empty so it is True when passed to bool(). See the Truth Value Testing section.

    这篇关于Python`None`传递给类型转换函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆