3

我有

try:
    a = list().append('hello')

但是aNoneType

try:
    b = list()
    b.append('hello')

并且b是一种list类型

我认为list()返回一个列表对象,list().append('hello')并将使用返回列表进行追加,但为什么是 的值a None

4

3 回答 3

9

list()确实返回了一个列表[](它反而返回。appendNone

例如:

>>> 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']
于 2013-03-10T10:17:25.200 回答
2
a = list().append('hello')

上面的行,将创建一个新列表,然后调用该append()方法,并将返回码存储append()到变量a中。并且由于 value 是None,它只是意味着该append()方法没有返回值。

要确认这一点,你可以试试这个:

>>> a = list()
>>> result = a.append('hello')
>>> print a
['hello']
>>> print result
None
于 2013-03-10T10:19:17.143 回答
2

你已经得到了你的问题的答案,但我只想指出,做你想做的事情的最好方法是两者都不是。它应该是:

a = [ 'hello' ]
于 2013-03-10T10:54:55.953 回答