为什么 len(None) return 不是 0?
Why doesn't len(None) return 0?
None
in Python 是一个对象。
>>> isinstance(None, object)
True
因此它可以使用像 __str__()
这样的函数
>>> str(None)
'None'
但为什么它对 __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()
它似乎是 Pythonic,即使变量是 None
而不仅仅是一个空列表,if list
也是可以接受的。
是否存在使用 len(None)
更多问题的情况?
len
仅对对象集合有意义 - None 不是集合。
你提到你想要这个:
because it comes up often as an error when a function returns None
instead of a list
据推测,您的代码如下:
list_probably = some_function()
for index in range(len(list_probably)):
...
并且正在获得:
TypeError: object of type 'NoneType' has no len()
注意以下几点:
len
用于确定 collections 的长度(例如 list
、dict
或 str
- 这些是Sized
个对象)。它 not 用于将任意对象转换为整数 - 它也没有为 int
或 bool
实现,例如;
- 如果
None
是可能的,您应该明确测试 if list_probably is not None
。使用例如if list_probably
会将 None
和空列表 []
视为相同,这可能不是正确的行为;和
- 通常有更好的方法来处理
range(len(...))
- 例如for item in list_probably
,使用zip
,等等
为 None
实施 len
只会 隐藏错误 其中 None
被错误地对待,就像其他一些对象一样 - 每个 the Zen of Python (import this
):
Errors should never pass silently.
同样 for item in None
会失败,但这并不意味着实施 None.__iter__
是个好主意!错误是一件好事 - 它们可以帮助您快速找到程序中的问题。
如果您有一个可能 return None
的项目,您可以使用 len(None or '')
并且它将 return 0
或第一个项目的长度,如果它是 not None
.
None
in Python 是一个对象。
>>> isinstance(None, object)
True
因此它可以使用像 __str__()
这样的函数>>> str(None)
'None'
但为什么它对 __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()
它似乎是 Pythonic,即使变量是 None
而不仅仅是一个空列表,if list
也是可以接受的。
是否存在使用 len(None)
更多问题的情况?
len
仅对对象集合有意义 - None 不是集合。
你提到你想要这个:
because it comes up often as an error when a function returns
None
instead of a list
据推测,您的代码如下:
list_probably = some_function()
for index in range(len(list_probably)):
...
并且正在获得:
TypeError: object of type 'NoneType' has no len()
注意以下几点:
len
用于确定 collections 的长度(例如list
、dict
或str
- 这些是Sized
个对象)。它 not 用于将任意对象转换为整数 - 它也没有为int
或bool
实现,例如;- 如果
None
是可能的,您应该明确测试if list_probably is not None
。使用例如if list_probably
会将None
和空列表[]
视为相同,这可能不是正确的行为;和 - 通常有更好的方法来处理
range(len(...))
- 例如for item in list_probably
,使用zip
,等等
为 None
实施 len
只会 隐藏错误 其中 None
被错误地对待,就像其他一些对象一样 - 每个 the Zen of Python (import this
):
Errors should never pass silently.
同样 for item in None
会失败,但这并不意味着实施 None.__iter__
是个好主意!错误是一件好事 - 它们可以帮助您快速找到程序中的问题。
如果您有一个可能 return None
的项目,您可以使用 len(None or '')
并且它将 return 0
或第一个项目的长度,如果它是 not None
.