ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Python Tutorial• 6 min read

Python OOP: Classes & Objects

Object-Oriented Programming, __init__, and self in Python

Python is an object-oriented programming language. Almost everything in Python is an object, with its properties and methods.

Creating Classes and The __init__() Constructor

Use the class keyword to create a class blueprint.

The __init__() function is the constructor called automatically whenever a new object is instantiated.

The self parameter is a reference to the current instance of the class.

Object-Oriented Programming Example
class Student:
    def __init__(self, name, track, xp=0):
        self.name = name
        self.track = track
        self.xp = xp
        
    def complete_lesson(self, xp_reward=20):
        self.xp += xp_reward
        print(f"{self.name} earned {xp_reward} XP! Total: {self.xp} XP")
        
    def get_status(self):
        return f"{self.name} is studying {self.track} (XP: {self.xp})"

# Create student instance
coder = Student("Emma", "Python & AI")
print(coder.get_status())
coder.complete_lesson(50)
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

What is the name of the special constructor method invoked when creating a new object instance in Python?