Your first class
class, __init__ and self, explained plainly.
🎬 Video version coming soon — read it now
Let's write a class line by line and understand each part.
class Student:
def __init__(self, name, branch, cgpa):
self.name = name
self.branch = branch
self.cgpa = cgpa
anil = Student("Anil", "CSE", 8.4)
bhavana = Student("Bhavana", "ECE", 9.1)
print(anil.name, anil.cgpa) # Anil 8.4
print(bhavana.branch) # ECEThe parts
class Student:defines a new class. Class names use CapWords.__init__(with two underscores on each side) is the constructor. Python calls it automatically when you create an object.selfis the object being created.self.name = namestores the name on that object.Student("Anil", "CSE", 8.4)creates an object. You pass everything exceptself; Python fills that in.
What is self, really?
When you write Student("Anil", "CSE", 8.4), Python does roughly this:
- Makes a new, empty Student object
- Calls
__init__(that_new_object, "Anil", "CSE", 8.4) - Hands you the object
So inside __init__, self is anil. For bhavana, self is bhavana. That's how each object keeps its own data.
Attributes are per object
anil.cgpa = 8.6 # changes only Anil
print(anil.cgpa, bhavana.cgpa) # 8.6 9.1Default values
class Student:
def __init__(self, name, branch, cgpa=0.0, city="Vizag"):
self.name = name
self.branch = branch
self.cgpa = cgpa
self.city = city
self.skills = [] # each student gets their own list
kavya = Student("Kavya", "IT")
kavya.skills.append("Python")Creating the empty list inside __init__ avoids the shared-default bug you met in the functions course.
Many objects
students = [
Student("Anil", "CSE", 8.4),
Student("Bhavana", "ECE", 9.1),
Student("Chaitanya", "IT", 7.2),
]
toppers = [s.name for s in students if s.cgpa >= 8]Compare s.name with s["name"]: it's shorter, and a typo like s.nmae gives a clear error.
Tip: Forgetting
self is the most common OOP error. If you see "takes 2 positional arguments but 3 were given", check that the method's first parameter is self.In one line
class defines a blueprint, __init__ sets each object's attributes, and self is the object currently being worked on.
Saved on this device. Sign in to keep progress everywhere.
Share with a friend