</>
CompilerOnline
Open Interactive Editor

Python Classes & Objects

Object-Oriented Python

Python is a multi-paradigm language, but it is heavily object-oriented. Almost everything in Python is an object, with its properties and methods. Classes serve as blueprints or templates for creating objects, allowing you to model real-world concepts in your code.

The __init__() Function

Use the __init__() function to assign values to object properties, or perform other initialization operations when the object is instantiated. It acts as the class constructor and is called automatically.

The self Parameter

The self parameter is a reference to the current instance of the class and is used to access variables that belong to the class. It does not have to be named self, but using it is a strong convention that makes code readable.

Python classes support inheritance, allowing a new class to inherit methods and properties from a parent class. This encourages code reuse. You can override parent methods in the child class by redefining them.

Python also provides encapsulation through private variables (prefixed with double underscores, e.g., __private_var), which prevents direct access from outside the class, protecting internal states.

Inheritance & Overriding Methods

Inheritance lets you construct a specialized class from a generic base class. When a child class implements a method with the same name as a base class method, it overrides the parent implementation to provide custom behavior.

python
class Animal:
    def speak(self): return "Grr"

class Dog(Animal):
    def speak(self): return "Woof"

d = Dog()
print("Dog says:", d.speak())
python
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def describe(self):
        return f"{self.name} is {self.age} years old."

p1 = Person("Charlie", 30)
print(p1.describe())