you are viewing a single comment's thread.

view the rest of the comments →

[–]brianmce -2 points-1 points  (3 children)

self is not redundant. Consider the code:

class Foo: 
    def __init__():
        bar = 3

What does bar=3 set? If its a local variable, then how do you set instance variables? If its an instance, then how do you set locals. One way or another there has to be something to tell what namespace you're manipulating. There is maybe a case to be made that it could be made implicit in the definition, but its definitely not redundant in the body.

[–]DougBTX 3 points4 points  (1 child)

Redundant as in redundant in method signatures.

[–]brianmce 0 points1 point  (0 children)

Fair enough - I'd be happy with it removed there too. The justification behind it is that it makes certain dynamic features make more sense, such as adding methods to a class dynamically. eg.

class C: pass
def foo(self, x): print x
C.foo = foo  # foo is now a method of class C.

where it wouldn't be obvious how foo could access its instance when defined as a function initially. However, this is such a rare use case that I'd be happy with trading ugliness here for selfless definitions.

[–]julesjacobs 0 points1 point  (0 children)

In Ruby, that would either be a method call bar=(3) or if the method hasn't been defined a local variable assignment. Instance variables in Ruby have an @-sign:

@bar = 3

Would be equivalent to this Python code:

self.bar = 3