tags:

views:

518

answers:

8

What is the purpose of the 'self' word in python. I understand it refers to the specific object created from that class, but i cant see why it explicitly needs to be added to very function as a parameter. To illustrate, in ruby, i could do this:

class myClass
    def myFunc(name)
        @name = name
    end
end

Which i understand, quite easily, However in python i need to include self:

class myClass:
    def myFunc(self, name):
        self.name = name

Can anyone talk me through this? its not something ive come across in my (admittedly limited) experience. Any help would be appreciated.

A: 

it's an explicit reference to the class instance object.

SilentGhost
I don't think this helps richzilla to understand the reason behind it.
Georg
uhm, you've made your opinion clear by downvoting
SilentGhost
+15  A: 

The reason you need to use self. is because Python does not use the @ syntax to refer to instance attributes. Python decided to do methods in a way that makes the instance to which the method belongs be passed automatically, but not received automatically: the first parameter of methods is the instance the method is called on. That makes methods entirely the same as functions, and leaves the actual name to use up to you (although self is the convention, and people will generally frown at you when you use something else.) self is not special to the code, it's just another object.

Python could have done something else to distinguish normal names from attributes -- special syntax like Ruby has, or requiring declarations like C++ and Java do, or perhaps something yet more different -- but it didn't. Python's all for making things explicit, making it obvious what's what, and although it doesn't do it entirely everywhere, it does do it for instance attributes. That's why assigning to an instance attribute needs to know what instance to assign to, and that's why it needs self..

Thomas Wouters
There is the exception of using *cls* instead of *self*, for example when using the *@classmethod* decorator.
Georg
@Georg: `cls` refers to the class object, not instance object
SilentGhost
The exception is when it's not a "regular" method, or "instance method", but something else -- a classmethod or a staticmethod or just a plain function :)
Thomas Wouters
+1 for a crystal-clear explanation
Maddy
+1  A: 

self is an object reference to the object itself, therefore, they are same. Python methods are not called in the context of the object itself. self in Python may be used to deal with custom object models or something.

SHiNKiROU
A: 
>>> import this
msw
-1: Until you post the resulting output (this post isn't useful to anyone new to the language).
Jon Cage
And if I post the resulting output, the merit of the comment is None. But thanks for playing.
msw
I disagree; explicit is better than implicit :-)
Jon Cage
+4  A: 

The following excerpts are from the Python documentation about self:

As in Modula-3, there are no shorthands [in Python] for referencing the object’s members from its methods: the method function is declared with an explicit first argument representing the object, which is provided implicitly by the call.

Often, the first argument of a method is called self. This is nothing more than a convention: the name self has absolutely no special meaning to Python. Note, however, that by not following the convention your code may be less readable to other Python programmers, and it is also conceivable that a class browser program might be written that relies upon such a convention.

For more information, see the Python documentation tutorial on classes.

Matthew Rankin
+1  A: 

As well as all the other reasons already stated, it allows for easier access to overridden methods.

You can call Class.some_method(inst)

example of where it's useful:

class C1(object):
    def __init__(self):
         print "C1 init"

class C2(C1):
    def __init__(self): #overrides C1.__init__
        print "C2 init"
        C1.__init__(self) #but we still want C1 to init the class too


>>> C2()
"C2 init"
"C1 init"
Wallacoloo
+1  A: 

I like this example:

class A: 
    foo = []
a, b = A(), A()
a.foo.append(5)
b.foo
ans: [5]

class A: 
    def __init__(self): 
        self.foo = []
a, b = A(), A()
a.foo.append(5)
b.foo
ans: []
kame
+2  A: 

I have been confused by this as well for quite a while and I don’t believe that the reason for this has got much to do with the often-pronounced explicit is better than implicit but that it is just following a simple analogy there.

Let’s take a simple vector class:

class Vector(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

Now, we want to have a method which calculates the length. What would it look like when we wanted to define it inside the class?

    def length(self):
        return math.sqrt(self.x ** 2 + self.y ** 2)

And, what should it look like when we were to define it as a global method/function?

def length_global(vector):
    return math.sqrt(self.x ** 2 + self.y ** 2)

So, the whole structure stays the same. Now, how can me make use of this? If we assume for a moment that we hadn’t written a length method for our Vector class, we could do this:

Vector.length_new = length_global
v = Vector(3, 4)
print v.length_new() # 5.0

This works, because the first parameter of length_global, can be re-used as the self parameter in length_new. This would not be possible without an explicit self.


Another way of understanding the need for the explicit self is to see where Python adds some syntactical sugar. When you keep in mind, that basically, a call like

v_instance.length()

is internally transformed to

Vector.length(v_instance)

it is easy to see where the self fits in. You don’t not actually write instance methods in Python; what you write is class methods which (must) take an instance as a first parameter. And therefore, you’ll have to place the instance parameter somewhere explicitly.

Debilski