1. Home
  2. Explore
  3. Computer Science
  4. Python OOP Course

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Python OOP Course

Object-Oriented Programming in Python

Introduction to OOP and Classes

Object-Oriented Programming (OOP) is a paradigm that helps organize code by grouping related data and behaviors into objects. In Python, every data type (strings, integers, lists) is itself an object, meaning it was created from a class. A class is a blueprint for creating objects. Understanding OOP is essential for writing reusable, maintainable code and is especially important for intermediate Python developers.

Why Use Classes Instead of Plain Variables?

Without classes, data for a single item might be stored in separate variables, but Python treats each variable independently — there is no explicit relationship between them. For example:

item1_name = "Phone"
item1_price = 100
item1_quantity = 5
item1_price_total = 500

Each variable has its own type (string, integer, etc.). Python does not know they belong together. By using a class, you create a custom data type where attributes (like name, price, quantity) are tied to a single object. This makes the relationship explicit and allows you to define methods that operate on that data.

Creating Your First Class

A class is defined with the class keyword followed by the class name (conventionally in PascalCase). Inside, you define attributes and methods.

class Item:
    pass  # placeholder to avoid errors

Instantiating Objects (Creating Instances)

An instance is a concrete object created from a class. Creating an instance is similar to calling a function — use the class name followed by parentheses.

item1 = Item()

You can then assign attributes to the instance using dot notation:

item1.name = "Phone"
item1.price = 100
item1.quantity = 5

The key difference from separate variables: all these attributes belong to the same item1 object, so Python understands they are related.

The type() Output

When you check the type of an instance, you see the custom class name:

print(type(item1))  # Output: <class '__main__.Item'>

This shows that you have created a new data type.

Methods in a Class

Methods are functions defined inside a class. They are accessible from instances and usually operate on the instance's data.

The self Parameter

Every method must accept at least one parameter: self. When you call a method on an instance, Python automatically passes the instance itself as the first argument. This is why self is a convention (strongly recommended) — it refers to the current instance.

class Item:
    def calculate_total_price(self):
        return self.price * self.quantity

Without self, calling the method would cause a TypeError because Python tries to pass the instance but the method accepts zero arguments.

Using Methods on Instances

item1 = Item()
item1.name = "Phone"
item1.price = 100
item1.quantity = 5
print(item1.calculate_total_price())  # Output: 500

You can define methods to encapsulate calculations or actions that make sense for the class.

The Constructor (__init__ Method)

The __init__ method (also called a constructor) is a special method that is automatically executed when an instance is created. It allows you to:

  • Receive required arguments at instantiation time

  • Assign attributes dynamically

  • Perform initial setup or validation

Syntax and Usage

class Item:
    def __init__(self, name, price, quantity):
        self.name = name
        self.price = price
        self.quantity = quantity

Now you must provide the arguments when creating an instance:

item1 = Item("Phone", 100, 5)

The __init__ method is only called once per object, right after the object is created.

Default Values for Parameters

You can set default values for parameters, making them optional:

def __init__(self, name, price, quantity=0):
    self.name = name
    self.price = price
    self.quantity = quantity

Now you can omit quantity:

item1 = Item("Phone", 100)  # quantity defaults to 0

Assigning Instance-Specific Attributes Outside the Constructor

Even if most attributes are set in __init__, you can still add extra attributes to specific instances later:

item2 = Item("Laptop", 1000)
item2.has_numpad = False  # only for this laptop

This flexibility allows handling exceptional properties without cluttering the constructor.

Type Hints and Validation in the Constructor

Type Hints

You can specify the expected data type of each parameter using type hints (a colon and the type). This improves readability and helps IDEs catch errors.

def __init__(self, name: str, price: float, quantity=0):
    self.name = name
    self.price = price
    self.quantity = quantity

Note: Type hints are not enforced at runtime — they are for documentation and static analysis tools.

Assert Statements for Validation

assert is a statement that checks a condition and raises an AssertionError if the condition is False. It is useful for validating data early.

def __init__(self, name: str, price: float, quantity=0):
    # Run validations
    assert price >= 0, f"Price {price} is not greater than or equal to zero!"
    assert quantity >= 0, f"Quantity {quantity} is not greater than or equal to zero!"
    self.name = name
    self.price = price
    self.quantity = quantity

If a negative value is passed, the program crashes immediately with a clear message, helping catch bugs early.

Class Attributes vs. Instance Attributes

Instance Attributes

Instance attributes are specific to each object. They are usually defined inside __init__ using self (e.g., self.name). Each instance has its own copy.

Class Attributes

Class attributes belong to the class itself, not to any one instance. They are shared across all instances of that class. Define them directly inside the class body (outside any method).

class Item:
    pay_rate = 0.8  # class attribute (20% discount)

Accessing Class Attributes

You can access a class attribute from the class itself or from an instance. If accessed from an instance, Python first looks for an instance attribute with that name. If not found, it falls back to the class attribute.

print(Item.pay_rate)   # 0.8
print(item1.pay_rate)  # 0.8 (if no instance pay_rate)

Overriding a Class Attribute on an Instance

You can assign an attribute with the same name on a specific instance, effectively overriding the class value for that instance only.

item2.pay_rate = 0.7  # instance attribute shadows the class attribute

Viewing All Attributes with __dict__

The magic attribute __dict__ returns a dictionary of all attributes belonging to the object.

print(Item.__dict__)   # includes class-level attributes
print(item1.__dict__)  # only instance attributes (e.g., name, price, quantity)

Practical Example: Applying a Discount

A method that applies a discount should access the pay rate from the instance level if you want to allow per-instance overrides.

class Item:
    pay_rate = 0.8

    def __init__(self, name: str, price: float, quantity=0):
        assert price >= 0
        assert quantity >= 0
        self.name = name
        self.price = price
        self.quantity = quantity

    def apply_discount(self):
        self.price = self.price * self.pay_rate  # uses instance's pay_rate (or class fallback)

Now you can set a different pay rate on specific items:

item1 = Item("Phone", 100, 5)
item2 = Item("Laptop", 1000, 3)
item2.pay_rate = 0.7

item1.apply_discount()  # uses class pay_rate (0.8) -> price becomes 80
item2.apply_discount()  # uses instance pay_rate (0.7) -> price becomes 700

Tracking All Instances with a Class Attribute

It is often useful to maintain a list of all instances created. You can use a class attribute (e.g., all) and append self inside __init__.

class Item:
    all = []  # class attribute to store all instances

    def __init__(self, name, price, quantity):
        # ...validations and attribute assignments...
        Item.all.append(self)  # add the new instance to the list

Now you can iterate over Item.all to do bulk operations, such as printing all names:

for instance in Item.all:
    print(instance.name)

Representing Objects with __repr__

The __repr__ method (short for "represent") defines a string representation of an object, useful for debugging and logging. It is called when you print an object or view it in the console.

Best Practice: Return a String That Could Recreate the Object

A common convention is to return a string that looks like the constructor call, so you could copy-paste it to recreate the instance.

class Item:
    def __repr__(self):
        return f"Item('{self.name}', {self.price}, {self.quantity})"

Now printing the all list shows readable representations:

print(Item.all)
# Output: [Item('Phone', 100, 5), Item('Laptop', 1000, 3)]

To make it generic (work with child classes), use self.__class__.__name__ to get the actual class name dynamically:

def __repr__(self):
    return f"{self.__class__.__name__}('{self.name}', {self.price}, {self.quantity})"

Reading Data from CSV Files

Motivation

Hardcoding instance data in your main file becomes messy for many items. A better approach is to separate data from code by storing item information in a CSV file (comma-separated values). Each row represents an item, and columns represent attributes.

Example items.csv:

name,price,quantity
Phone,100,5
Laptop,1000,3
Keyboard,75,10

Using csv.DictReader

Python's built-in csv module can read CSV files and return each row as a dictionary (column names become keys).

import csv

class Item:
    @classmethod
    def instantiate_from_csv(cls):
        with open('items.csv', 'r') as f:
            reader = csv.DictReader(f)
            items = list(reader)
        for item in items:
            Item(
                name=item['name'],
                price=float(item['price']),
                quantity=int(item['quantity'])
            )

Note: CSV values are read as strings, so you must convert numbers to int or float.

Class Methods and Static Methods

Class Methods (@classmethod)

Class methods are methods that operate on the class itself, not on instances. They receive the class as the first argument (conventionally named cls). They are often used as alternative constructors to instantiate objects from different data sources.

class Item:
    @classmethod
    def instantiate_from_csv(cls):
        with open('items.csv', 'r') as f:
            reader = csv.DictReader(f)
            items = list(reader)
        for item in items:
            cls(  # use cls to create instances of the class
                name=item['name'],
                price=float(item['price']),
                quantity=int(item['quantity'])
            )

You call class methods on the class itself (not on instances):

Item.instantiate_from_csv()

Static Methods (@staticmethod)

Static methods are methods that do not receive an implicit first argument (neither self nor cls). They behave like regular functions but are namespaced inside the class. Use them when the method is logically related to the class but does not need access to instance or class data.

class Item:
    @staticmethod
    def is_integer(num):
        # Check if a number is an integer (count out floats that are .0)
        if isinstance(num, float):
            return num.is_integer()
        elif isinstance(num, int):
            return True
        else:
            return False

You can call static methods on the class or on instances (though instances are rarely used):

print(Item.is_integer(7))    # True
print(Item.is_integer(7.5))  # False
print(Item.is_integer(7.0))  # True (is_integer() returns True for 7.0)

When to Use Which

  • Class methods: When you need to create instances from structured data (CSV, JSON, YAML). They receive cls and can access class attributes or call other class methods.

  • Static methods: When the method has a logical connection to the class but does not need to access instance or class state. They are essentially helper functions placed inside the class.

Inheritance

Inheritance allows you to create a new class (child) that reuses the attributes and methods of an existing class (parent). This avoids code duplication and models hierarchical relationships.

Basic Syntax

class Phone(Item):  # Phone inherits from Item
    pass

Now all instances of Phone have access to all methods and attributes defined in Item, including __init__, calculate_total_price, apply_discount, etc.

Overriding the Constructor in a Child Class

Often a child class needs additional attributes (e.g., broken_phones). You can define a new __init__ in the child, but you should call the parent’s __init__ using super() to avoid duplicating common attribute assignments.

class Phone(Item):
    def __init__(self, name, price, quantity, broken_phones=0):
        # Call parent __init__
        super().__init__(name, price, quantity)

        # Additional validation and assignment specific to Phone
        assert broken_phones >= 0, f"Broken phones {broken_phones} is not >= 0"
        self.broken_phones = broken_phones

Using super().__init__() ensures that all parent logic (validations, attribute assignments, appending to all list) is executed.

Accessing Parent Attributes and Methods

The child class inherits all public and protected attributes and methods. If the parent class stores instances in Item.all, child instances will also be added there because super().__init__() runs the parent's __init__, which includes Item.all.append(self).

Polymorphism through Inheritance

Polymorphism means "many forms." In OOP, it allows the same method name to behave differently depending on the object’s class. Because of inheritance, you can call a parent method on any child instance, and the method works correctly. You can also override a method in the child to provide specific behavior.

class Keyboard(Item):
    pay_rate = 0.7  # override class attribute for keyboards

Now keyboard.apply_discount() uses pay_rate = 0.7 (if accessed via self.pay_rate).

Encapsulation

Encapsulation is the principle of restricting direct access to an object's internal data and only allowing modification through controlled methods (getters and setters). This prevents accidental corruption of data and allows you to add validation or logic when reading or writing attributes.

Private Attributes with Double Underscore

In Python, prefixing an attribute name with double underscore (__) triggers name mangling, making it harder to access from outside the class. This is Python's way of supporting private attributes.

class Item:
    def __init__(self, name, price):
        self.__name = name   # effectively private
        self.__price = price

Now you cannot access __name directly from an instance; doing so raises an AttributeError. However, it can still be accessed via _Item__name (mangled name), but this is not recommended.

Properties (Getters and Setters)

Properties allow you to define methods that are accessed like attributes. They let you control read and write behavior.

  • Getter (@property): Defines what happens when you read the attribute.

  • Setter (@attribute.setter): Defines what happens when you assign a new value.

class Item:
    def __init__(self, name, price):
        self.__name = name
        self.__price = price

    @property
    def name(self):
        # Getter: return the private value
        return self.__name

    @name.setter
    def name(self, value):
        # Setter: validate before assigning
        if len(value) > 10:
            raise Exception("The name is too long!")
        self.__name = value

Now you can read and write item.name as if it were a regular attribute, but the setter can enforce rules.

Important: When you define a property with the same name as an attribute (e.g., name), you must use a different underlying private attribute (e.g., __name) to avoid infinite recursion. Inside the property, access the private version, not the property itself.

Read-Only Properties

If you define only a getter (no setter), the attribute becomes read-only — users cannot assign a new value.

@property
def price(self):
    return self.__price

Attempting item.price = 10 raises AttributeError: can't set attribute.

Why Use Encapsulation?

  • Validation: Ensure data integrity (e.g., price cannot be negative).

  • Change management: Later, you can change internal representation without breaking external code.

  • Logging/Debugging: Add print statements or logging inside getters/setters.

Abstraction

Abstraction means hiding complex implementation details and showing only the essential features of an object. In Python, this is achieved by making internal methods private using double underscore.

Private Methods

Just like private attributes, prefixing a method name with __ makes it private (name-mangled). These methods can only be called from within the class, not from instances.

class Item:
    def send_email(self):
        self.__connect()
        self.__prepare_body()
        print("Email sent")

    def __connect(self):
        print("Connecting to SMTP server...")

    def __prepare_body(self):
        print("Preparing email body...")

Now item.send_email() works, but item.__connect() will raise an AttributeError.

Purpose of abstraction: The user of the class only needs to know that send_email() works — they do not need to understand the underlying connection and preparation steps. This simplifies usage and hides complexity.

Polymorphism

Polymorphism allows a single function, method, or operator to behave differently based on the type of object it operates on. It is the ability to present the same interface for different data types.

Example with Built-in len()

len() works on strings, lists, tuples, dictionaries, and any object with a __len__ method. It returns the number of items in that specific object:

print(len("Hello"))    # 5 (characters)
print(len([1, 2, 3]))  # 3 (elements)

The same function name (len) produces different results depending on the argument.

Polymorphism with Inheritance

When you call a method on an instance of a child class, Python looks up the method in the child class first; if not found, it goes up to the parent class. This allows you to call the same method name on objects of different classes, each of which may have its own implementation (override).

class Phone(Item):
    def apply_discount(self):
        self.price = self.price * 0.9  # 10% discount for phones

class Laptop(Item):
    pass  # uses parent's apply_discount (20% off)

phone = Phone("iPhone", 1000)
laptop = Laptop("MacBook", 2000)
phone.apply_discount()   # phone price becomes 900
laptop.apply_discount()  # laptop price becomes 1600

Both objects respond to apply_discount(), but each gives a different result based on its class.

Polymorphism through Duck Typing

Python is dynamically typed, so polymorphism often relies on duck typing: "If it walks like a duck and quacks like a duck, it's a duck." As long as an object has the required methods, it can be used polymorphically regardless of its actual class.

class Duck:
    def quack(self):
        print("Quack")

class Person:
    def quack(self):
        print("I'm quacking like a duck!")

def make_quack(obj):
    obj.quack()

make_quack(Duck())    # Quack
make_quack(Person())  # I'm quacking like a duck!

Four Key Principles of OOP — Summary

Principle

Description

Python Implementation

Encapsulation

Restrict direct access to data; only allow modification through methods.

Private attributes __attr, properties (@property, @setter)

Abstraction

Hide unnecessary details; expose only essential interfaces.

Private methods __method, public methods as the API

Inheritance

Create new classes that reuse and extend existing class features.

class Child(Parent): and super().__init__()

Polymorphism

Use a single interface to represent different underlying types.

Method overriding, duck typing, len() like functions

Organizing Code into Multiple Files

As a project grows, it is good practice to separate each class into its own .py file and import them into a main script.

Example Structure

project/
├── item.py        # Item class
├── phone.py       # Phone class (inherits Item)
├── keyboard.py    # Keyboard class (inherits Item)
└── main.py        # Creates instances and runs the program

Importing Classes

In phone.py:

from item import Item

class Phone(Item):
    # ...

In main.py:

from item import Item
from phone import Phone
from keyboard import Keyboard

Item.instantiate_from_csv()
phone = Phone("Galaxy", 800, 5, broken_phones=1)
keyboard = Keyboard("Mechanical", 150, 10)

This keeps the code modular and maintainable.


These notes cover all major concepts from the course: classes, instances, __init__, instance and class attributes, methods, type hints, assertions, CSV data handling, class methods, static methods, inheritance, super(), encapsulation with properties, abstraction with private methods, and polymorphism. Each topic includes definitions, code examples, and best practices. Use this reference to study and apply OOP principles in your own Python projects.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent