Python Classes & Objects

Object-oriented programming in Python.

✍️ 3 exercises + code challenge in this lesson

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.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services