On 20/04/2012 21:03, Jan Sipke wrote:
Can you explain why there is a difference between the following two
statements?
a = []
a.append(1)
print a
[1]
print [].append(1)
None
append is a method of the list object []. Methods, in general, both do
something to the objects of which they are attributes, and return a
value (in fact they work pretty much like any other Python function; if
a is an instance of type A, then calling a.method(x, y, etc) is the same
thing as calling A.method(a, x, y, etc), which is no different from
calling any other function). Both of the two code examples you posted
are doing the same thing, namely appending the value one to a list and
returning None. But in the first case you can't see that the method is
returning None since the Python interpreter doesn't bother to write a
function's output when that output is None. But you would have seen it
if you had explicitly asked the interpreter to show it, like so:
>>> a = []
>>> print a.append(1)
None
Similarly, the second example is changing the list on which it was
called in the same way that the first example changed a; but since you
didn't assign the list in question to any variable, there's no way for
you to refer to it to see its new value (in fact it just gets deleted
right after being used since its reference count is zero).
In general there's no reason why
>>> a.method(arguments)
>>> print a
will print the same thing as
>>> print a.method(arguments)
since a method doesn't assign the value it returns to the instance on
which it is called; what it does to the instance and what it returns are
two completely different things.
--
Hate music? Then you'll hate this:
http://tinyurl.com/psymix
--
http://mail.python.org/mailman/listinfo/python-list