📘 Lesson · Lesson 85
self and __init__
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.
self और __init__
💡 एक नज़र में
__init__ constructor है जो object बनने पर चलता है। self current object को refer करता है, जिससे आप उसका data store और access करते हैं।
Example
Python
class Student:
def __init__(self, name, marks):
self.name = name # self object पर data रखता है
self.marks = marks
def show(self):
print(self.name, "got", self.marks)
s = Student("Aman", 88)
s.show()Aman got 88
self क्यों?
selfइस object के data को दूसरों से अलग करता है।- हर method का पहला parameter
selfहोता है (Python अपने आप pass करता है)।
सारांश
- __init__ object बनने पर चलता है और initial values set करता है।
- self current object को refer करता है; self.x से data store/read करें।