Python Classes & Objects Tutorial - __init__, self, inheritance, super() Explained
Video: Python Classes & Objects Tutorial - __init__, self, inheritance, super() Explained by Taught by Celeste AI - AI Coding Coach
Watch full page →Python Classes & Objects Tutorial - __init__, self, inheritance, super() Explained
This tutorial covers the fundamentals of Python classes and objects, showing how to define classes with the class keyword and initialize them using the __init__ method. It also explains instance attributes via self, creating and modifying objects, and introduces inheritance and method overriding using super().
Code
# Define a basic class with attributes and methods
class Dog:
def __init__(self, name, breed, age):
# Initialize instance attributes
self.name = name
self.breed = breed
self.age = age
def bark(self):
# Instance method using self
return f"{self.name} says Woof!"
# Create an instance of Dog
rex = Dog("Rex", "German Shepherd", 5)
print(rex.bark()) # Output: Rex says Woof!
# Define a base class
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def speak(self):
return f"{self.name} makes a sound."
# Inherit from Animal and extend functionality
class Cat(Animal):
def __init__(self, name, age, color):
# Call parent constructor to initialize name and age
super().__init__(name, age)
self.color = color
# Override speak method
def speak(self):
return f"{self.name} says Meow!"
# Create a Cat instance
whiskers = Cat("Whiskers", 3, "Tabby")
print(whiskers.speak()) # Output: Whiskers says Meow!
Key Points
- Use the
classkeyword and__init__method to define and initialize objects. selfrefers to the instance and is used to access attributes and methods.- Inheritance allows a class to reuse and extend functionality from a parent class.
super().__init__()calls the parent class constructor to set up inherited attributes.- Method overriding lets subclasses customize or replace parent class behavior.