为什么len(None)不返回0?

Sup*_*Man 11 python nonetype

None 在Python中是一个对象.

>>> isinstance(None, object)
True
Run Code Online (Sandbox Code Playgroud)

因此它可以使用像__str __()这样的函数

>>> str(None)
'None'
Run Code Online (Sandbox Code Playgroud)

但为什么不对__len __()做同样的事情呢?

>>> len(None)
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    len(None)
TypeError: object of type 'NoneType' has no len()
Run Code Online (Sandbox Code Playgroud)

似乎Pythonic if list也是可接受的,即使变量是None而不仅仅是一个空列表.

是否有案例可以len(None)解决更多问题?

orl*_*rlp 15

len 只对对象集合有意义 - None不是集合.


jon*_*rpe 14

你提到你想要这个:

因为当函数返回None而不是列表时,它经常作为错误出现

据推测,你有以下代码:

list_probably = some_function()
for index in range(len(list_probably)):
    ...
Run Code Online (Sandbox Code Playgroud)

并得到:

TypeError: object of type 'NoneType' has no len()
Run Code Online (Sandbox Code Playgroud)

请注意以下事项:

  • len是用于确定的长度集合(例如一个list,dictstr-这些Sized对象).它不是用于将任意对象转换为整数 - 它也不是为了实现,int或者是bool,例如;
  • 如果None有可能,你应该明确测试if list_probably is not None.使用eg if list_probably会对待None并且空列表[]相同,这可能不是正确的行为; 和
  • 通常有一种更好的方法来处理列表range(len(...))- 例如for item in list_probably,使用zip等.

实现lenfor None只会隐藏错误,None正在处理错误,就像其他一些对象一样 - 根据Python的Zen(import this):

错误不应该默默地传递.

同样for item in None会失败,但这并不意味着实施None.__iter__是一个好主意!错误是一件好事 - 它们可以帮助您快速找到程序中的问题.


小智 7

如果您有一个可能会返回的项目,None您可以使用len(None or '')and it willreturn 0或第一个项目的长度(如果是)not None