📘 Lesson · Lesson 85
self and __init__
self and __init__
💡 At a Glance
__init__ is the constructor that runs when an object is created. self refers to the current object, letting you store and access its data.
Example
Python
class Student:
def __init__(self, name, marks):
self.name = name # self stores data on the object
self.marks = marks
def show(self):
print(self.name, "got", self.marks)
s = Student("Aman", 88)
s.show()Aman got 88
Why self?
selfdistinguishes this object's data from others.- Every method's first parameter is
self(Python passes it automatically).
Summary
- __init__ runs on object creation and sets initial values.
- self refers to the current object; use self.x to store/read its data.
💻 Live Code Editor
This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.