By richzilla

2010-04-25 20:22:28 8 Comments

What is the purpose of the self word in Python? I understand it refers to the specific object created from that class, but I can't see why it explicitly needs to be added to every function as a parameter. To illustrate, in Ruby I can do this:

class myClass
    def myFunc(name)
        @name = name

Which I understand, quite easily. However in Python I need to include self:

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

Can anyone talk me through this? It is not something I've come across in my (admittedly limited) experience.


@prosti 2019-05-23 16:32:30

self is inevitable.

There was just a question should self be implicit or explicit. Guido van Rossum resolved this question saying self has to stay.

So where the self live?

If we would just stick to functional programming we would not need self. Once we enter the Python OOP we find self there.

Here is the typical use case class C with the method m1

class C:
    def m1(self, arg):
        print(self, ' inside')

ci =C()
print(ci, ' outside')
print(hex(id(ci))) # hex memory address

This program will output:

<__main__.C object at 0x000002B9D79C6CC0>  outside
<__main__.C object at 0x000002B9D79C6CC0>  inside

So self holds the memory address of the class instance. The purpose of self would be to hold the reference for instance methods and for us to have explicit access to that reference.

Note there are three different types of class methods:

  • static methods (read: functions),
  • class methods,
  • instance methods (mentioned).

@Bugs Buggy 2018-08-01 10:53:25

The use of the argument, conventionally called self isn't as hard to understand, as is why is it necessary? Or as to why explicitly mention it? That, I suppose, is a bigger question for most users who look up this question, or if it is not, they will certainly have the same question as they move forward learning python. I recommend them to read these couple of blogs:

1: Use of self explained

Note that it is not a keyword.

The first argument of every class method, including init, is always a reference to the current instance of the class. By convention, this argument is always named self. In the init method, self refers to the newly created object; in other class methods, it refers to the instance whose method was called. For example the below code is the same as the above code.

2: Why do we have it this way and why can we not eliminate it as an argument, like Java, and have a keyword instead

Another thing I would like to add is, an optional self argument allows me to declare static methods inside a class, by not writing self.

Code examples:

class MyClass():
    def staticMethod():
        print "This is a static method"

    def objectMethod(self):
        print "This is an object method which needs an instance of a class, and that is what self refers to"

PS:This works only in Python 3.x.

In previous versions, you have to explicitly add @staticmethod decorator, otherwise self argument is obligatory.

@Akash Kandpal 2018-01-12 04:45:25

First of all, self is a conventional name, you could put anything else (being coherent) in its stead.

It refers to the object itself, so when you are using it, you are declaring that .name and .age are properties of the Student objects (note, not of the Student class) you are going to create.

class Student:
    #called each time you create a new Student instance
    def __init__(self,name,age): #special method to initialize

    def __str__(self): #special method called for example when you use print
        return "Student %s is %s years old" %(,self.age)

    def call(self, msg): #silly example for custom method
        return ("Hey, %s! "+msg)

#initializing two instances of the student class

#using them
print bob.age
print alice #this one only works if you define the __str__ method
print"Come here!") #notice you don't put a value for self

#you can modify attributes, like when alice ages
print alice

Code is here

@ytpillai 2015-05-25 16:04:31

Python is not a language built for Object Oriented Programming unlike Java or C++.

When calling a static method in Python, one simply writes a method with regular arguments inside it.

class Animal():
    def staticMethod():
        print "This is a static method"

However, an object method, which requires you to make a variable, which is an Animal, in this case, needs the self argument

class Animal():
    def objectMethod(self):
        print "This is an object method which needs an instance of a class"

The self method is also used to refer to a variable field within the class.

class Animal():
    #animalName made in constructor
    def Animal(self):
        self.animalName = "";

    def getAnimalName(self):
        return self.animalName

In this case, self is referring to the animalName variable of the entire class. REMEMBER: If you have a variable within a method, self will not work. That variable is simply existent only while that method is running. For defining fields (the variables of the entire class), you have to define them OUTSIDE the class methods.

If you don't understand a single word of what I am saying, then Google "Object Oriented Programming." Once you understand this, you won't even need to ask that question :).

@Laryx Decidua 2015-07-24 09:37:38

+1 because of the distinction between staticMethod() and objectMethod(self). I would like to add that in order to invoke the first, you would say Animal.staticMethod(), while objectMethod() needs an instance: a = Animal(); a.objectMethod()

@user441521 2016-01-12 18:20:04

What you are saying isn't 100% true. That's just a convention. You can still call the static method from an object created. You just won't be able to use any class members because you didn't declare a self. I can even call Animal.objectMethod(animalObj) to call the non static. Basically this means a static method is only a method that doesn't use member variables. There shouldn't be any need to declare self. It's a silly language requirement I think. Languages like Lua and C++ give you obj variables behind the scenes.

@john 2017-07-25 01:47:35

The only answer that makes sense! Thank you!!!!!!!!!!!!!!!!!!!!!!!

@Cees Timmerman 2017-09-21 18:25:58

You made a useless animalName string declaration and crashing animalName method.

@ytpillai 2017-09-21 18:29:16

To @user441521, python is meant for scripting not oop , it does not excel in oop standards. To timmerman, this was written for educational purpose, its a minor error, only those who simply copy paste without understanding, which SO finds unethical, will have problems with the answer.

@Cees Timmerman 2017-09-21 18:34:16

@ytpillai Irrelevant. Confusing and incorrect code should not be presented as an answer.

@ytpillai 2017-09-21 18:35:15

Fixed the question

@Cees Timmerman 2017-09-21 18:38:09

def getAnimalName to not clobber the string you're trying to return, and self refers to the instance of the class, not any field inside of it.

@Patrick Artner 2019-02-18 18:05:45

For defining fields (the variables of the entire class), you have to define them OUTSIDE the class methods. ... The differentiation between class attributes and instance attributes is very vague - you can create instance attributes just fine inside instance methods - creating class attributes also works if you prefix them witht the classes name ... Animal.ClawDamage = 200 inside def getAnimalName(self): works just fine -any Animal will have that attribute

@Debilski 2010-04-28 00:03:33

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


is internally transformed to


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.

@Jeeyoung Kim 2010-11-22 21:37:34

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.

@teddy teddy 2012-09-07 19:43:09

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.

@RussW 2013-09-06 09:46:18

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.

@Karoly Horvath 2014-03-15 16:16:34

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

@Debilski 2014-03-16 14:52:44

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

@Wes Turner 2014-11-08 18:50:06

So, with Ruby, would refactoring between a function and a method require searching for each of the @variables and removing the @ sign? (Great answer, thanks!)

@mgilson 2016-04-30 02:46:53

I think that even more technically, v_instance.length() is transformed to Vector.length.__get__(v_instance, Vector)(), but that might make the waters a little more muddy than we want them ;-)

@Debilski 2016-04-30 09:38:13

@mgilson: Or even something like type(v_instance) instead of Vector before that.

@lfender6445 2017-02-14 17:43:23

as someone who is learning python after ruby, the last paragraph greatly summarizes the distinction of self

@Sergio 2017-03-17 19:53:37

"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." This explained it more clearly than the text directly above.

@kiwicomb123 2018-06-12 20:32:07

The last paragraph is very good. This should be the top answer.

@Gaurav Nishant 2012-08-30 16:37:23

Its use is similar to the use of this keyword in Java, i.e. to give a reference to the current object.

@LEMUEL ADANE 2012-10-26 12:01:24

class myClass: def myFunc(this, name): = name

@user441521 2016-01-12 18:10:32

I'm surprised nobody has brought up Lua. Lua also uses the 'self' variable however it can be omitted but still used. C++ does the same with 'this'. I don't see any reason to have to declare 'self' in each function but you should still be able to use it just like you can with lua and C++. For a language that prides itself on being brief it's odd that it requires you to declare the self variable.

@skyking 2015-08-27 07:31:02

Is because by the way python is designed the alternatives would hardly work. Python is designed to allow methods or functions to be defined in a context where both implicit this (a-la Java/C++) or explicit @ (a-la ruby) wouldn't work. Let's have an example with the explicit approach with python conventions:

def fubar(x):
    self.x = x

class C:
    frob = fubar

Now the fubar function wouldn't work since it would assume that self is a global variable (and in frob as well). The alternative would be to execute method's with a replaced global scope (where self is the object).

The implicit approach would be

def fubar(x)
    myX = x

class C:
    frob = fubar

This would mean that myX would be interpreted as a local variable in fubar (and in frob as well). The alternative here would be to execute methods with a replaced local scope which is retained between calls, but that would remove the posibility of method local variables.

However the current situation works out well:

 def fubar(self, x)
     self.x = x

 class C:
     frob = fubar

here when called as a method frob will receive the object on which it's called via the self parameter, and fubar can still be called with an object as parameter and work the same (it is the same as C.frob I think).

@sw123456 2015-06-28 05:47:02

When objects are instantiated, the object itself is passed into the self parameter.

enter image description here

Because of this, the object’s data is bound to the object. Below is an example of how you might like to visualize what each object’s data might look. Notice how ‘self’ is replaced with the objects name. I'm not saying this example diagram below is wholly accurate but it hopefully with serve a purpose in visualizing the use of self.

enter image description here

The Object is passed into the self parameter so that the object can keep hold of its own data.

Although this may not be wholly accurate, think of the process of instantiating an object like this: When an object is made it uses the class as a template for its own data and methods. Without passing it's own name into the self parameter, the attributes and methods in the class would remain as a general template and would not be referenced to (belong to) the object. So by passing the object's name into the self parameter it means that if 100 objects are instantiated from the one class, they can all keep track of their own data and methods.

See the illustration below:

enter image description here

@udarH3 2015-08-10 08:31:16

Hey there, when accessing Bob's attributes for example by "", you actually accesing bob() so to speak from the 'init' right?

@sw123456 2015-08-10 08:48:10

When you write in the above comment, you are implying that bob has a method called name() due to the fact that you added brackets after name. In this example however there is no such method. '' (which has no parenthesis) is directly accessing the attribute called name from the init (constructor) method. When bob's speak method is called it is the method which accesses the name attribute and returns it in a print statement. Hope this helps.

@udarH3 2015-08-10 09:07:28

Yeah without paranthesis i wanted to write sry. So the value of name you actually get it and not of because as far as i know and name are 2 different variable. Thanks

@sw123456 2015-08-10 09:18:08

No, you get the value of, which for the bob object is actually, because the object's name is passed into the self parameter when it is created (instantiated). Again, hope this helps. Feel free to upvote main post if it has.

@sw123456 2015-08-10 09:23:35

Name is assigned to at instantiation. After an object is created, all variables that belong to the object are those prefixed with 'self.' Remember that self is replaced with the object's name when it is created from the class.

@fishiwhj 2016-04-19 13:03:37

Very clear explanation. But, how to validate its correctness?

@penta 2017-11-05 09:44:03

This is how you explain stuff ! nice job :)

@Arjun Sreedharan 2014-01-26 17:31:58

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.

@Seth 2014-10-08 02:37:50

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

@Rio 2015-06-03 19:13:48

This is called as magic answer __magic__()

@SIslam 2015-06-13 15:36:35

This is already answered in the latter portion of Debilski's answer..

@Bernard 'Beta Berlin' Parah 2016-06-28 08:41:08

This nailed it for me!

@Cees Timmerman 2017-09-21 18:15:20

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

@Spandy 2017-12-12 01:00:17

This should have been the answer !! To the point and precise

@saurav 2018-01-28 10:10:55

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

@kmario23 2014-11-15 07:54:27

Take a look at the following example, which clearly explains the purpose of self

class Restaurant(object):  
    bankrupt = False

    def open_branch(self):
        if not self.bankrupt:
           print("branch opened")

#create instance1
>>> x = Restaurant()
>>> x.bankrupt

#create instance2
>>> y = Restaurant()
>>> y.bankrupt = True   
>>> y.bankrupt

>>> x.bankrupt

self is used/needed to distinguish between instances.

@user441521 2016-01-12 18:13:08

Yes, I think we know why self is used, but the question is why does the language make you explicitly declare it. Many other languages don't require this and a language which prides itself on being brief, you'd think they would just give you the variable behind the scenes to use like Lua or C++ (this) does.

@geekidharsh 2018-04-13 18:12:25

@kmario23 You're response was from here:‌​ned Please always acknowledge original authors when posting answers as your own.

@TheEnglishMe 2014-01-26 18:11:21

In the __init__ method, self refers to the newly created object; in other class methods, it refers to the instance whose method was called.

self, as a name, is just a convention, call it as you want ! but when using it, for example to delete the object, you have to use the same name: __del__(var), where var was used in the __init__(var,[...])

You should take a look at cls too, to have the bigger picture. This post could be helpful.

@dan-klasson 2013-08-16 17:23:12

It’s there to follow the Python zen “explicit is better than implicit”. It’s indeed a reference to your class object. In Java and PHP, for example, it's called this.

If user_type_name is a field on your model you access it by self.user_type_name.

@Ponkadoodle 2010-04-25 20:31:43

As well as all the other reasons already stated, it allows for easier access to overridden methods; you can call Class.some_method(inst).

An 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"

@ninjagecko 2011-06-22 00:27:23

I will demonstrate with code that does not use classes:

def state_init(state):
    state['field'] = 'init'

def state_add(state, x):
    state['field'] += x

def state_mult(state, x):
    state['field'] *= x

def state_getField(state):
    return state['field']

myself = {}
state_add(myself, 'added')
state_mult(myself, 2)

print( state_getField(myself) )
#--> 'initaddedinitadded'

Classes are just a way to avoid passing in this "state" thing all the time (and other nice things like initializing, class composition, the rarely-needed metaclasses, and supporting custom methods to override operators).

Now let's demonstrate the above code using the built-in python class machinery, to show how it's basically the same thing.

class State(object):
    def __init__(self):
        self.field = 'init'
    def add(self, x):
        self.field += x
    def mult(self, x):
        self.field *= x

s = State()
s.add('added')    # self is implicitly passed in
s.mult(2)         # self is implicitly passed in
print( s.field )

[migrated my answer from duplicate closed question]

@Cees Timmerman 2017-09-21 18:18:15

I wish Python sugarcoated the handlers as well as Ruby does.

@Thomas Wouters 2010-04-25 20:25:37

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

@Georg Schölly 2010-04-25 20:30:13

There is the exception of using cls instead of self, for example when using the @classmethod decorator.

@SilentGhost 2010-04-25 20:33:15

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

@Thomas Wouters 2010-04-25 20:55:11

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 :)

@SingleNegationElimination 2010-11-22 22:13:54

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

@Jules G.M. 2012-12-12 20:46:31

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?

@Bakuriu 2013-09-20 19:07:01

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

@Borat Sagdiyev 2014-03-18 18:01:47

@ThomasWouters - Is it correct to say that "self" keyword of python is EXACTLY the same as the "this" keyword of Java ? If not, what are the differences ?

@Wes Turner 2014-11-08 18:42:27

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

@user441521 2016-01-12 18:24:03

It would be nice if self was given to us behind the scenes like Lua and C++ (this) does. " 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." Good thing you ended it that way because coming from other languages I was about to argue the first part of that. Using white space for meaning is NOT an explicit thing at all and it's at the core of python. I'd argue compared to other languages Python isn't very explicit at all. So why stop with explicitly declaring self is the question.

@noobninja 2016-08-18 18:11:50 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.

@ivanleoncz 2017-03-22 18:59:33

I think that this statement deserves a bold: the first parameter of methods is the instance the method is called on.

@Alisson 2018-03-28 03:07:51

Python instance methods look like C# extension methods, where the first parameter refers to the instance, regardless of the name you choose for it. In my opinion, it's ugly and unnecessary, but if I wanted a language which suited all my preferences, I should probably make my own programming language.

@Puck 2018-07-30 08:31:46

This would be explicit only if method would be call like: o = myClass(); myFunc(o, "name");

@bruno desthuilliers 2019-02-25 14:22:46

This answer is missing a very important part on the _true_reasons for the explicit self, which - as explained here - is that python "methods" are actually just plain functions, so the language needed a way to pass the current instance to the function.

@kame 2010-04-26 16:02:48

I like this example:

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

class A: 
    def __init__(self): = []
a, b = A(), A()
ans: []

@teddy teddy 2012-09-07 19:45:30

so vars without self is simply static vars of the class, like in java

@Konstantin 2014-03-27 19:18:39

teddy teddy, you aren't entirely correct. The behavior (static or non-static like) depends not only on self but also on the variable type. Try to do the first example with simple integer instead of list. The result would be quite different.

@Radon Rosborough 2014-08-06 18:29:41

Actually, my question with this is why are you allowed to say in the first example, rather than Clearly foo belongs to the class...

@Paarth 2014-10-29 00:25:50

You can call static members from instances of the object in most languages. Why is that surprising?

@LegendaryDude 2017-07-12 17:07:40

@RadonRosborough Because in the first example, a and b are both labels (or pointers) for A() (the class). references the A().foo class method. In the second example, though, a becomes a reference to an instance of A(), as does b. Now that they are instances instead of the class object itself, self allows the foo method to operate on the instances.

@Matthew Rankin 2010-04-25 20:29:08

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.

@Ming-Tang 2010-04-25 20:26:35

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.

@SilentGhost 2010-04-25 20:24:57

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

@Georg Schölly 2010-04-25 20:30:43

I don't think this helps richzilla to understand the reason behind it.

@BlueTomato 2017-10-09 14:51:27

@SilentGhost: you have nailed it. I am impressed. if I understand it correctly: I do create an object as an instance of the defined class and the self parameter refers to that object? I understand self refers in implicit way to the class itself but it would be great if you explain your answer a bit more.

Related Questions

Sponsored Content

15 Answered Questions

[SOLVED] Call a parent class's method from child class in Python?

28 Answered Questions

[SOLVED] What does if __name__ == "__main__": do?

18 Answered Questions

[SOLVED] What __init__ and self do on Python?

  • 2009-03-09 05:09:51
  • 950693 View
  • 674 Score
  • 18 Answer
  • Tags:   python oop self

38 Answered Questions

[SOLVED] What does the "yield" keyword do?

23 Answered Questions

[SOLVED] What is the difference between @staticmethod and @classmethod?

15 Answered Questions

[SOLVED] What are metaclasses in Python?

34 Answered Questions

[SOLVED] What is Inversion of Control?

34 Answered Questions

[SOLVED] What is the difference between an interface and abstract class?

8 Answered Questions

22 Answered Questions

[SOLVED] When to use self over $this?

  • 2008-09-30 06:23:06
  • Casey Watson
  • 656852 View
  • 1896 Score
  • 22 Answer
  • Tags:   php class scope

Sponsored Content