Source

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:

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

Newsletter

Ă—

If you liked what you read then I am sure you will enjoy a newsletter of the content I create. I send it out every other month. It contains new stuff that I make, links I find interesting on the web, and occasional discount coupons for my book. Join the 5000+ other people who receive my newsletter:

I send out the newsletter once every other month. No spam, I promise + you can unsubscribe at anytime

✍️ Comments

nabil

thank you for this explcation

Walt

I think I get it now – thanks!

cmholmes181
In reply to Walt

Yes, same I think I get it now as well

akanhastra gowda

thanx nic tut….

dusadv

Thank you. It saved me a heck of trouble

Bob Barker

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.

Bob Barker

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?

Bob Barker

nevermind… i found the answer using reddit.

sorry, anon…

bradozman

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.

Yasoob
In reply to bradozman

Hey bradozmen. I hope that have understood your problem correctly. You can subclass the Remotecontrol class in a new file and implement the function in the subclass. After that create a new object from the subclass and use it. For more info on subclassing read this http://stackoverflow.com/questions/1607612/python-how-do-i-make-a-subclass-from-a-superclass

bradozman

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.

Diba

Thank you so much! It makes sense now!

embition

Still doesn’t make sense to me lol… I’ll try re-reading this when I have more patience.

Md. Abul Hossain Hashem

Thank you. It saved many time

Yasoob
In reply to Md. Abul Hossain Hashem

I am glad that it helped you :)

Anna

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?

Imran Mohamed

In technology, a tiny little concept understanding makes the change, thanks a lot for the article… :)

Eric

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

Poornima

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

Amar Shukla
In reply to Poornima

Yes your code is correct.

Victoria Rodriguez

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

Yasoob
In reply to Victoria Rodriguez

Hey! I am sorry for disappointing you. :) However, fellas is a gender neutral internet slang word. It is supposed to be welcoming. I am sorry if it made you feel otherwise. http://www.urbandictionary.com/define.php?term=fellas

Molly
In reply to Victoria Rodriguez

Thanks for saying this Victoria! I thought the same thing when I started reading.

John Smith
In reply to Victoria Rodriguez

Don’t be disappointed. It’s a gender neutral term in spite of what Simon and Molly say.

Niels Weel

Good and clear explanation of the self and even a bit of the class OOP.

Richard Bao

Thank you so much! I get i am getting to understand it now!

D

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?

Alopex
In reply to D

Once x becomes bound to the Restaurant class, x.bankrupt is just the data attribute that stores whether x is bankrupt or not. Try calling the class method, x.open_branch(), to have the code check x.bankrupt and then print accordingly. For reference, https://docs.python.org/3/tutorial/classes.html#instance-objects

Ivanhercaz

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.

Regards, Iván

Yasoob
In reply to Ivanhercaz

I am glad you found it useful :)

Nada b

Very clear, thank you !

Yasoob
In reply to Nada b

I am glad you found it useful :)

Jennifer Yeomans

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

Say something

Send me an email when someone comments on this post.

Thank you!

Your comment has been submitted and will be published once it has been approved. 😊

OK