The self variable in python explained

Hi there fellas. 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 .


25 thoughts on “The self variable in python explained

  1. Pingback: Storing and Loading Data with JSON | Bite Sized Python Tips

  2. Bob Barker says:

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

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

  4. bradozman says:

    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.

  5. bradozman says:

    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.

  6. Pingback: NotesIndex: Index of Notes | Never Ending Security

  7. Anna says:

    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?

  8. Eric says:

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

  9. Poornima says:

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

  10. 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 :-/

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s