Paul McGuire wrote: > > There's nothing wrong with returning self from a mutator. This was a common > idiom in Smalltalk (the syntax for this was "^self", which was probably the > most common statement in any Smalltalk program), and permitted the chaining > of property mutators into a single line, each invoking a mutator and > returning self, which was then used to invoke the next mutator, etc.
Various Java APIs encourage this kind of behaviour, too, or at least encouraged it in earlier times. However, as I wrote, there is some kind of understanding that undoubtedly results from a policy decision in the design of Python's built-in types that saves the programmer from having to question the nature of a return value in such a way. [...] > But with mutators that return self, a client could write any of these: > > bx = Box().length(100).width(50).height(20) > bx = Box().width(50).height(20).length(100) > bx = Box().width(50).length(100).height(20) > ...etc... > > and the results are the same. This is very convenient, and I've often thought about doing such things in my own APIs, but there can sometimes be subtle problems introduced into programs when you decide to change the nature of such a mutator, or if you have another type/class whose mutators are of a different nature, such that the width method produces a new Box object (which is quite similar to what the questioner seemed to have in mind) instead of mutating (or failing to mutate) the existing object. Indeed, it may be important to know whether you're creating new objects or not, and without metadata the most convenient way to communicate this is quite probably to define a rigid interface (after all, why should width or append return an object?) which cannot be implemented on immutable things. Paul -- http://mail.python.org/mailman/listinfo/python-list