🏗️

How to Create Classes in Python

PythonIntermediate

Build object-oriented programs with classes.

Code Example

Python
# Classes in Python
class Animal:
    def __init__(self, name, species):
        self.name = name
        self.species = species
    
    def speak(self):
        return f"{self.name} ({self.species}) makes a sound"
    
    def __repr__(self):
        return f"Animal('{self.name}', '{self.species}')"

class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name, "Canine")
        self.breed = breed
    
    def speak(self):
        return f"{self.name} says Woof!"
    
    def fetch(self, item):
        return f"{self.name} fetches the {item}"

# Usage
dog = Dog("Rex", "German Shepherd")
print(dog.speak())
print(dog.fetch("ball"))
print(f"Breed: {dog.breed}")
print(f"Species: {dog.species}")

Explanation

Classes use __init__ for initialization, self for instance reference, and support inheritance with super().

Related Tutorials