What is the use of self in python?
joshua-brown0010
Posted on November 27, 2020
The reason you need to use self. is because Python does not use the @ syntax to refer to instance attributes. Python decided to do methods in a way that makes the instance to which the method belongs be passed automatically, but not received automatically: the first parameter of methods is the instance the method is called on. That makes methods entirely the same as functions, and leaves the actual name to use up to you (although self is the convention, and people will generally frown at you when you use something else.) self is not special to the code, it's just another object.
Python could have done something else to distinguish normal names from attributes -- special syntax like Ruby has, or requiring declarations like C++ and Java do, or perhaps something yet more different -- but it didn't. Python's all for making things explicit, making it obvious what's what, and although it doesn't do it entirely everywhere, it does do it for instance attributes. That's why assigning to an instance attribute needs to know what instance to assign to, and that's why it needs self..
To add to the other answers...
You could declare variables within a class without using the self reference, but then those variables would be shared by all instances of that class, which may not be what you intended. In your example, self.age = age and self.name = name are declaring "instance variables" (as opposed to "class variables"), the values of which would be unique to the instantiated objects of that class. Otherwise, all students would have the same name and age!
Let's say you have a class ClassA which contains a method methodA defined as:
Read more
Posted on November 27, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.