python

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:

x.bankrupt

The above command is same as:

Restaurant().bankrupt

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
False

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

>>> x.bankrupt
False

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

 

Advertisement: 

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

Advertisements
Standard

28 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.
    Example..
    Rem.settrace(true)
    Print rem.Tracing
    >>true

    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.settrace(true)
    >> self is not defined.
    Remotecontrol.settrace(true)
    >>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 :-/

      • Simon says:

        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? 🙂

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

  11. D says:

    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?

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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