Categories
class oop python self

What is the `self` parameter in class methods?

1270

self refers to the specific object instance created from a class. But why must every method explicitly include self as a parameter?

class MyClass:
    def func(self, name):
        self.name = name

Conversely, in Ruby, there is no self:

class MyClass
    def func(name)
        @name = name
    end
end

12

  • 125

    You may find interesting this essay “Why explicit self has to stay” by Guido van Rossum: neopythonic.blogspot.com/2008/10/…

    – unutbu

    Apr 25, 2010 at 20:35

  • 14

    See also “Why must ‘self’ be used explicitly in method definitions and calls”: docs.python.org/faq/…

    – unutbu

    Apr 25, 2010 at 20:38

  • 38

    “Which i understand, quite easily” — Quite subjective, don’t you think? What makes @name more intuitive than self.name? The latter, IMO, is more intuitive.

    – Santa

    Apr 28, 2010 at 0:12


  • 3

    Although to play devils advocate its very easy to forget to add an additional argument to each method and have bizarre behavior when you forget which makes it hard for beginners. IMHO I rather be specific about unusual things like static methods then normal behavior like instance methods.

    – Adam Gent

    Apr 28, 2010 at 0:29

  • 17

    That’s the key difference between a function and a class method. A function is floating free, unencumbered. A class (instance) method has to be aware of it’s parent (and parent properties) so you need to pass the method a reference to the parent class (as self). It’s just one less implicit rule that you have to internalize before understanding OOP. Other languages choose syntactic sugar over semantic simplicity, python isn’t other languages.

    Jan 17, 2012 at 6:59

764

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..

14

  • 25

    @Georg: cls refers to the class object, not instance object

    Apr 25, 2010 at 20:33

  • 20

    @SilentGhost: Actually, the name of the first parameter is whatever you want it to be. On class methods, the convention is to use cls and self is used conventionally for instance methods. If I wanted, I could use self for classmethods and cls for instance methods. I could also use bob and fnord if I liked.

    Nov 22, 2010 at 22:13

  • 73

    I find it interesting that the community didn’t choose this instead of self. Does self have some history that I’m not aware of in older programming languages?

    Dec 12, 2012 at 20:46


  • 28

    @Julius The self came from Modula-3’s conventions, see this answer for further details on this choice. (Disclaimer: its mine).

    – Bakuriu

    Sep 20, 2013 at 19:07

  • 10

    @Julius The self keyword (Smalltalk, 1980) predates the this keyword (from C++). See: stackoverflow.com/questions/1079983/…

    Nov 8, 2014 at 18:42


581

Let’s say you have a class ClassA which contains a method methodA defined as:

def methodA(self, arg1, arg2):
    # do something

and ObjectA is an instance of this class.

Now when ObjectA.methodA(arg1, arg2) is called, python internally converts it for you as:

ClassA.methodA(ObjectA, arg1, arg2)

The self variable refers to the object itself.

5

  • 135

    I read all the other answers and sort of understood, I read this one and then it all made sense.

    – Seth

    Oct 8, 2014 at 2:37

  • 5

    Why not keep those guts inside, though, like Ruby does?

    Sep 21, 2017 at 18:15

  • But in __init__(self) method, it accepts self, then even without creating the object, how does it refer to itself?

    – saurav

    Jan 28, 2018 at 10:10

  • 1

    This doesn’t answer the question though. The OP was asking about why self has to be explicitly defined.

    – Rain

    Jul 13, 2021 at 8:05

  • Why then a new function is generated for every instance of classA? It seems from this internal conversion that is more appropriate to say that methodA is method of the class and not of the instance.

    – ado sar

    yesterday

436

Let’s take a simple vector class:

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

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

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

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

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

So the whole structure stays the same. 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 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.

11

  • 4

    Vector.length_new = length_global… I actually started to use syntax like this in my class declarations. Whenever I only want to inherit some of the methods from another class, I just explicitly copy the reference to the methods.

    Nov 22, 2010 at 21:37

  • 2

    would it be fair to say that python’s “instance method” is simply a syntactic sugar of static global methods (as in Java or C++) with an instance object passed in to package multiple attributes? — well this is kind of half-true since in polymorphism, the more important purpose of “this” (as in java) or “self” is to give u the correct implementation of methods. Python does have this. so calling myobj.someMethod() is equal to TheClassOfMyObj.someMethod(myobj) in python. note that the “TheClassOfMyObj” is automatically figured out by python from “self”, otherwise u’d have to find that out.

    Sep 7, 2012 at 19:43

  • 3

    Infact, not only are instance methods just class methods, but methods are just functions which are members of a class, as the Vector.length_new = length_global shows.

    – RussW

    Sep 6, 2013 at 9:46

  • 1

    “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.” – it would work just the same. it would be re-used for the implicit self… the second example is a circular reasoning – you have to explicitly place self there, because python needs the explicit self.

    Mar 15, 2014 at 16:16

  • 1

    @KarolyHorvath: Sure, it would also be possible to have a language with a model where internally defined methods do not need an explicit self but externally defined methods do. But I’d say there is some consistency in requiring the explicit self in both cases, which makes it a legitimate reason to do it this way. Other languages may choose different approaches.

    – Debilski

    Mar 16, 2014 at 14:52