Consistency in Python

Paul McGuire ptmcg at austin.rr._bogus_.com
Fri Aug 25 07:02:44 EDT 2006


"Paul Boddie" <paul at boddie.org.uk> wrote in message 
news:1156497650.974905.196140 at 74g2000cwt.googlegroups.com...
<snip>
> Moreover, append and insert return
> no result because the change occurs within an existing object - if you
> were to return a reference to the changed object, it would be the same
> reference as the one you already had.
>

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.  For 
instance, you could have a class like this:

class Box(object):
    def __init__(self):
        self.ln = 0
        self.wd = 0
        self.ht = 0
    def length(self,ln):
        self.ln = ln
        return self
    def width(self,w):
        self.wd = w
        return self
    def height(self,h):
        self.ht = h
        return self
    volume = property(lambda self:self.ln*self.wd*self.ht)

bx = Box().length(100).width(50).height(20)
print bx.volume


I guess this is sort of a trivial example, and in its triviality, even 
borders on un-Pythonic.  But it is useful when you want to support a large 
set of object attributes, without creating an init method with many, many 
args.  Even in this case, an init method that takes length, width and height 
args must always get them specified in the correct order, or use named args. 
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.

-- Paul





More information about the Python-list mailing list