Classes

Classes are the foundation of Object-Oriented Programming (OOP) in Python. They allow you to create user-defined data structures that encapsulate data and functionality. This topic covers high level Introduction of classes, how to define them, create objects, and OOP principles.

Key Concepts

Class Definition

How to define a class using the class keyword.

class Person:
    pass

Attributes

Variables that hold data specific to a class.

class Person:
    name = "John"
    age = 30

Methods

Functions defined within a class that operate on its attributes.

class Person:
    def greet(self):
        print("Hello!")

Constructor (__init__ method)

Special method for initializing new objects.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

Inheritance

Mechanism for creating new classes based on existing ones.

class Animal:
    def speak(self):
        print("Animal speaks")

class Dog(Animal):
    def bark(self):
        print("Dog barks")

Encapsulation

Bundling data and methods together while restricting access to some components.

class BankAccount:
    def __init__(self, balance):
        self.__balance = balance

    def deposit(self, amount):
        self.__balance += amount

    def get_balance(self):
        return self.__balance

Polymorphism

Ability to use a shared interface for different data types or classes.

class Bird:
    def speak(self):
        print("Chirp!")

class Cat:
    def speak(self):
        print("Meow!")

def make_sound(animal):
    animal.speak()

make_sound(Bird())
make_sound(Cat())

Magic Methods

Special methods that enable operator overloading and advanced class behavior.

class Book:
    def __init__(self, title):
        self.title = title

    def __str__(self):
        return f"Book title: {self.title}"

book = Book("Python 101")
print(book)