Why do we use self attribute in defining an instance of class? What is it's specific purpose? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 9

Why do we use self attribute in defining an instance of class? What is it's specific purpose?

Eg. class Cat: def __init__(self, color, legs): self.color = color self.legs = legs

17th Apr 2019, 2:50 AM
Prince PS[Not_Active]
Prince PS[Not_Active] - avatar
4 Answers
+ 12
Self is an object reference to the object itself. It is similar to this keyword of other programming languages. Plz refer to this link : https://stackoverflow.com/questions/2709821/what-is-the-purpose-of-self
17th Apr 2019, 4:10 AM
Arushi Singhania
Arushi Singhania - avatar
+ 8
You can use any valid variable name, it's just that self is convention. It is an instance of a class i.e object reference to itself.
17th Apr 2019, 4:39 AM
Dan Rhamba
Dan Rhamba - avatar
+ 1
#Meta
24th Apr 2019, 7:01 AM
Akili Holmes
Akili Holmes - avatar
+ 1
It is the constructor in Python, strongly private with two underscores at the beginning.
28th Apr 2019, 3:00 AM
Brent Grigsby
Brent Grigsby - avatar