SyntaxStudy
Sign Up
Python Intermediate 11 min read

OOP Basics

Object-Oriented Programming in Python

Classes and Objects

class Animal:
    def __init__(self, name, sound):
        self.name = name
        self.sound = sound

    def speak(self):
        return f"{self.name} says {self.sound}"

dog = Animal("Dog", "Woof")
print(dog.speak())

Inheritance

class Dog(Animal):
    def __init__(self, name):
        super().__init__(name, "Woof")

    def fetch(self):
        return f"{self.name} fetches the ball!"

rex = Dog("Rex")
print(rex.speak())
print(rex.fetch())

Properties

class Circle:
    def __init__(self, radius):
        self._radius = radius

    @property
    def area(self):
        import math
        return math.pi * self._radius ** 2
Pro Tip

Use __repr__ to define a developer-friendly string representation of your class.