explicit self revisited

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Sat Nov 11 21:42:18 EST 2006


On Sat, 11 Nov 2006 22:39:37 +0100, Peter Maas wrote:

[snip]
> let self be represented by the dot, e.g. replace
> 
> class someTest(unittest.TestCase):
>     def setUp(self):
>         self.ly = yList()
>         self.m1 = self.ly[0].message
>         self.m2 = self.ly[1].message
>         self.m3 = self.ly[2].message
 
> by
> 
> class x(unittest.TestCase):
>     def .setUp():
>         .ly = yList()
>         .m1 = .ly[0].message
>         .m2 = .ly[1].message
>         .m3 = .ly[2].message

On the assumption that Peter was sincere, and not trolling, I thought I'd
make a point-by-point response, but then X crashed and took my post with
it. So here's the brief version.

Implicit self will never be used for Python, because it is redundant so
long as there is a need for explicit self, and there is a need for
explicit self because there are a number of basic, dare I say
*fundamental* programming techniques that require an explicit self.

For example, delegation.

class MyClass(Parent):
    def method(self, arg):
        Parent.method(self, arg)
        # what are you going to write? Parent.method(,arg) maybe?

Here's another fundamental technique that implicit self breaks.

class MyList(list):
    def __iadd__(self, other):
        # in-place addition
        other = transform(other) # do something to the argument
        super(MyList, self).__iadd__(other) # call the superclass
        # could be written .__class__.__iadd__(other)
        # BUT be aware the semantics are NOT the same!
        return self  # and return the suitably modified instance

You can't explicitly return the instance unless you have an explicit name
for it. (And if you are thinking of creating more magic syntax that
implicitly returns self, just don't bother.)

Even more fundamentally, any time you need to pass the instance to a
function, you need an explicit self. (Delegation is a special case of this.)

    def __str__(self):
        # I like semicolons and dislike square brackets.
        return ';'.join(self)



-- 
Steven.




More information about the Python-list mailing list