Python is an object-oriented language. A class is a blueprint; an object is an instance of it.
__init__() is the constructor; it runs when an object is created.
self refers to the current object and is the first parameter of every method.
__str__() defines how the object is printed.
Class attributes are shared by all instances; instance attributes belong to one object.
💡 Key Takeaways: Python Classes & Objects
Mastering Python Classes & Objects helps you write clean and reliable Python code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.
Python Classes & Objects Code Example
Python
class Student:
school = "CodesInTech Academy" # class attribute
def __init__(self, name, marks):
self.name = name # instance attributes
self.marks = marks
def grade(self):
return "A" if self.marks >= 85 else "B" if self.marks >= 70 else "C"
def __str__(self):
return f"{self.name} ({self.marks}) - grade {self.grade()}"
s1 = Student("Hina", 91)
s2 = Student("Bilal", 74)
print(s1)
print(s2)
print(s1.school)
Free sign-in required · Google login available
Python Classes & Objects Practice Exercises
Check what you learned in “Python Classes & Objects”.
/ 3 solved
Fill in the blank
Name the constructor method.
class Car:
def (self, brand):
self.brand = brand
✓ Correct!Not quite. Try again.
Multiple choice
What does self refer to?
✓ Correct!Not quite. Try again.
Code challenge
Create a class Dog with an __init__(self, name) and a method bark() that returns name + " says Woof". Print Dog("Moti").bark().
Write the code in the live editor. Your answer is checked automatically.