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:
) 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 .
thank you for this explcation
I think I get it now — thanks!
Yes, same I think I get it now as well
thanx nic tut….
Thank you. It saved me a heck of trouble
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.***”
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?
nevermindโฆ i found the answer using reddit.
sorry, anonโฆ
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.
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
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.
Thank you so much! It makes sense now!
Still doesn’t make sense to me lol… I’ll try re-reading this when I have more patience.
Thank you. It saved many time
I am glad that it helped you ๐
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?
In technology, a tiny little concept understanding makes the change, thanks a lot for the article… ๐
I’m leaving this comment just to say please give your variables meaningful names like ‘myRest.’ or joesResturant’ , not ‘x’. Jesus christ.
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”)
Yes your code is correct.
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
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
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. ๐
Thanks for saying this Victoria! I thought the same thing when I started reading.
Don’t be disappointed. It’s a gender neutral term in spite of what Simon and Molly say.
Good and clear explanation of the self and even a bit of the class OOP.
Thank you so much! I get i am getting to understand it now!
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?
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
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
I am glad you found it useful ๐
Very clear, thank you !
I am glad you found it useful ๐
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 ๐