[Tutor] Re: .sort() vs .sort

Jeff Shannon jeff@ccvcorp.com
Fri Dec 13 15:16:58 2002


Charlie Clark wrote:

>>  file_list.sort
>>  file_list.sort()
>>
>>I did that, and everything worked fine.
>>
>>Now, I'm not surprised that the version without parens didn't work -- 
>>it's not supposed to.  But I'm intrigued that it didn't give a syntax 
>>error or exception, or, as far as I can tell, have any effect at all.  
>>How did Python interpret that line?
>>    
>>
>
>Let's see if I can beat Danny or Magnus to this. The answer is really easy 
>but it's something that bites me a lot, too.
>
>.sort  - is an attribute
>.sort() - is a method
>
>ie. they are different beasts. file_list.sort asks the object whether it 
>has an attribute .sort or provideCompare the following two examples
>

Actually, that's not really true.  file_list.sort *is* an attribute... 
but it's also a method.  The difference is that without the parens, it 
resolves to an object reference (the object being a method object). 
 *With* the parens, it resolves the object reference and then calls that 
reference as a function.  Methods are just an attribute that happens to 
be a function (and has a little extra magic to pass the 'self' reference 
in).

As for what Python does when it sees 'file_list.sort' by itself on a 
line, or even 'x' by itself... well, it does exactly what you've told it 
to do -- nothing. ;)  It resolves the reference, and then looks to see 
if there's any operations to be done on the object it's found.  It 
doesn't see any operations there, so it quietly drops the reference into 
the garbage collector.  There *is* a special case, though -- when 
running Python in interactive mode (typing directly into an interpreter 
window, or in IDLE's or PythonWin's interactive window), the interactive 
interpreter won't just drop the reference.  It figures that you'd 
probably like to see *something* happen, and the most sensible thing to 
do with an object that's not operated on is to just display it.  So, if 
you do this in the interactive interpreter, you will get a response of 
'42' or of  '<method list.sort of list instance at 0x80028a04>' or whatever.

Jeff Shannon
Technician/Programmer
Credit International