[Tutor] Need Explanation...

ALAN GAULD alan.gauld at btinternet.com
Sat Dec 10 23:42:20 CET 2011


>> Smalltalk's mechanism  stands in stark contrast to the mixed
>> model in Python. (OTOH Smalltalk overall is a frustrating
>> experience for me, I would like to love it but never quite
>> get there... :-)
>
>Personally, I found that returning a copy of a seemed more logical- after all, 
>if you return 4 to b, then adding 2 to b wouldn't make 4 equal 6.
>
>But the object is modified in both cases. 
But returning a copy loses the biggest advantage of returning self, 
namely, that you can chain methods.

As it is you have to do:

a.append(42)
a.sort()
b = a[3]

With self returns you can write

b = a.append(42).sort().[3]

The best we can do in Python is two lines:

a.append(42)
b = sorted(a)[3]

Being able to chain methods is a very powerful idiom.
Just look at how often people do it with strings.

aList = myFile.read().strip().split()

is a particularly common pattern that relies on string modifier 
operations returning the modified string.

> Better than silently returning None for sure.
>
>Of course, by silently returning None, you can just go on with your daily life 
>and be happily ignorant of any return value; As you can with any default return value.
After all printf() in C returns the number of characters printed, but 
when was the last time you saw code that did anything with the 
return value from printf()?
Similarly with None, most Pythonistas just ignore it. The same applies to self, 
you would just ignore it if you didn't need it.


in other more strongly typed languages, the void functions/methods tend 
>to alter other variables and situations more than, for example, ints.  Sorry I don't get that bit. a void function doesn't alter anything. 
At least no more than an int function can.


I feel myself that it is no more trouble to simply type 'a.append(4); b = a'.But that's not chaining methods that's setting two variables to refer to the same object.
Not particularly useful most of the time.

Alan g.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20111210/2ec5e6ec/attachment-0001.html>


More information about the Tutor mailing list