The self variable in python explained

Hi everyone! In this post I am going to teach you about the self variable in python. I have seen many beginners struggling to grasp the concept of self variable. If you are one of them then this post is for you. So lets start by making a class involving the self variable.

A simple class :

So here is our class:

class Restaurant(object):
    bankrupt = False
    def open_branch(self):
        if not self.bankrupt:
            print("branch opened")

First let me explain the above code without the technicalities. First of all we make a class Restaurant. Then we assign it a property “bankrupt” which is currently false. After that we assign it a function open_branch which can only occur if “bankrupt” is False which means that the Restaurant has some money.

Making a resturant:

Now that we have made a class for a Restaurant, lets actually make a resturant:

x = Restaurant()

Now x is a Restaurant which has a property bankrupt and a function open_branch. Now we can access the property bankrupt by typing:


The above command is same as:


Now you can see that self refers to the bound variable or object. In the first case it was x because we had assigned the Restaurant class to x whereas in the second case it referred to Restaurant(). Now if we have another Restaurant y, self will know to access the bankrupt value of y and not x. For example check this example:

>>> x = Restaurant()
>>> x.bankrupt

>>> y = Restaurant()
>>> y.bankrupt = True
>>> y.bankrupt

>>> x.bankrupt

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.

class Restaurant(object):
    bankrupt = False
    def open_branch(this):
        if not this.bankrupt:
            print("branch opened")

Free Tip:

However self is not a reserved keyword in python it’s just a strong convention. Many people say that why do we have to write self ? Why can’t we have it set automatically like in Java ? Someone also filed a PEP (improvement suggestion) in which he suggested to remove the explicit assignment of self keyword. However Guido Van Rossum (the maker of python) wrote a blogpost in which he told why explicit self has to stay.

I hope you have understood to concept of self. If you have any other questions then feel free to comment. If you liked this post then make sure that you share it on facebook, tweet it on twitter and follow our blog.

You might also like:
) Python socket network programming
args and **kwargs in python explained
*) Making a url shortener in python


Access your favorite Windows Applications and Programming software from your Android/iOS device with a virtual desktop by – one of the best Desktop-as-a-Service provider , You can also go for Hyper-V or Servers to create testing Environment from .

37 thoughts on “The self variable in python explained”

  1. Shouldn’t the “open_branch” function’s if-statement say,

    if self.bankrupt == True:
    print (“branch opened”)

    Because you said,

    “Then we assign it a property “bankrupt” which is currently false. ***After that we assign it a function open_branch which can only occur if “bankrupt” is False which means that the Restaurant has some money.***”

  2. Same person from a second ago,

    I even mistyped what I meant to correct.

    I mean shouldn’t the if-statement say,

    if self.bankrupt == False:
    print(“branch opened”)

    This is to make the idea of your class make more sense?

    If a restaurant IS BANKRUPT, that means bankrupt = True.

    Why would the branch be opened then if it IS bankrupt?

  3. I get this.
    My problem is there is an assessment I have to do that has 3 files.
    3rd file is irrelevant to my problem..

    The second file has a class called remotecontrol

    The first file imports remotecontrol and creates an instance.

    Rem = remotecontrol()

    Now in remotecontol I can correctly use self to assign functions and properties and it works fine from the 1st file that creates the instance.
    Print rem.Tracing

    Now here’s the problem.

    We are not allowed to modify the file that creates the instance of remotecontol.

    All our code has to be within remotecontol itself.

    When in remotecontol how do I refer to the same instance?
    Example in remotecontol…
    >> self is not defined.
    >>remotecontrol is not defined.

    Any ideas?

    If I was allowed to just write my code in the same file as where the instance is created and refer to all the classes properties using the instance name it wouldn’t be a problem. But I am not allowed to edit that file.

  4. Hey YASOOB

    Thanks mate but Im not allowed create a new file either. I figured it out though.

    I just got my methods to call each other creating a sort of loop with if conditions.

    Methods calling methods calling methods until the program is complete.

  5. It does not make any sence. It is not about self at all. You do not use self in the code. Only at one place so how it is about self variable. What exactly about self variable you are trying explain?

  6. I’m leaving this comment just to say please give your variables meaningful names like ‘myRest.’ or joesResturant’ , not ‘x’. Jesus christ.

  7. Thanks you for very nice explanation. Could you please elaborate on object parameter which is present while declaring a class.. What is its significance? Also do we need to explicitly declare class variables ?
    I mean is below code is correct?
    class Restaurant(object):
    def __init__(self):
    self.bankrupt = false;
    def open_branch(self):
    if not self.bankrupt:
    print(“branch opened”)

  8. this helped me understand a little better…my first lesson did a horrible job of explaining the concept. although coming to this page to be greeted with ‘hi there fellas’ was actually a bit disappointing being that.. I’m a girl :-/

      1. Mmm, fellas is definitely not gender neutral but I have no doubt it wasnt your intention to specifically exclude females in the conversation. Especially with the recent issues highlighting some horrible attitudes towards women in the industry, we should be making an effort to be more inclusive. Something like this may seem minor, but on the other hand it’s a minor thing to just not use gender specific words. I am certainly guilty of unconscious bias myself, and using terms like “hey guys” (very similar!). My boss (male) actually called me out on that once, and it made me think “yeah, actually, good point!” and I try not to use it now…at least not in professional life anyway. People don’t like being told they’re being offensive when they didn’t mean anything by it. It’s very irritating to some, and seems very unfair to them. But we shouldn’t be defensive and just dismiss it as “political correctness” (as if somehow being correct is a bad thing), we should be bigger than that, not take it personally, and just make a little bit of effort to be inclusive. It takes a lot less energy 🙂 This is more a general comment than a criticism towards you yasoob: I can assume you are sincere in not wanting to cause offense. But i would’ve personally just replied with “Oopse good point! Sorry, I’ll change it”. Why not? 🙂

      2. Hey Simon,

        You are right. I am sorry I just didn’t realize the seriousness of my mistake. English is my third language and apparently I was misguided about the appropriateness of “fellas”.

        Thank you and Victoria for pointing out my lack of understanding. 🙂

  9. I get it, I just don’t understand why the print statement was never executed when you called x.bankrupt. Seems to me that if the value of x.bankrupt is false, then the branch is open and the call to print should be executed. Am I missing something?

  10. Thank you very much for your explanation, Yasoob! Sometimes it could be hard to understand for a non-professional programmer this mechanisms. And very nice the post of Guido van Rossum about why we have to keep “self” in the Python core.


  11. Interesting explanation. It’s just a shame the only thing some people took from that was your greeting! Thank you for the time you took to write this 🙂

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s