我有
try:
a = list().append('hello')
但是a
是NoneType
try:
b = list()
b.append('hello')
并且b
是一种list
类型
我认为list()
返回一个列表对象,list().append('hello')
并将使用返回列表进行追加,但为什么是 的值a
None
?
list()
确实返回了一个空列表[]
(它反而返回。append
None
例如:
>>> lst = []
>>> lst.append('hello') # appends 'hello' to the list
>>> lst
['hello']
>>> result = lst.append('world') # append method returns None
>>> result # nothing is displayed
>>> print result
None
>>> lst # the list contains 'world' as well now
['hello', 'world']
a = list().append('hello')
上面的行,将创建一个新列表,然后调用该append()
方法,并将返回码存储append()
到变量a
中。并且由于 value 是None
,它只是意味着该append()
方法没有返回值。
要确认这一点,你可以试试这个:
>>> a = list()
>>> result = a.append('hello')
>>> print a
['hello']
>>> print result
None
你已经得到了你的问题的答案,但我只想指出,做你想做的事情的最好方法是两者都不是。它应该是:
a = [ 'hello' ]