Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The basic elements of OOP in Python are classes, instances, attributes, methods, inheritance, composition, and protocols such as special methods. Together, they let you keep related state and behavior understandable—but Python does not require every program to use classes. Use OOP when it clarifies ownership, invariants, or extension; use functions and built-in data structures when they are simpler.

Objects and classes: the starting point

You already use objects. A string has methods such as .upper(), and a list has methods such as .append(). A class defines a type: it describes the data an object can hold and the operations it supports. An instance is one object created from that class.

Python’s tutorial describes classes as a way of “bundling data and functionality together.” A class is useful when several values and operations belong together; it is not a requirement that every noun in a problem become a class.

Define a class and create instances

This small task class gives each task its own title and completion state:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
class Task:
    def __init__(self, title):
        self.title = title
        self.completed = False

    def complete(self):
        self.completed = True

    def status(self):
        return "done" if self.completed else "open"

first = Task("Read about classes")
second = Task("Write an example")
first.complete()

print(first.status())   # done
print(second.status())  # open

__init__ initializes an instance that Python has already created; it is not the allocation mechanism itself. Assignments such as self.title and self.completed create instance attributes. Each call to Task(...) produces separate state.

What self means

In an instance method, Python supplies the instance as the first argument. self is the conventional parameter name, not a keyword. These calls are equivalent:

first.complete()
Task.complete(first)

The first form is normally clearer. Omitting self from the method definition prevents the instance from being received correctly.

Instance variables and class variables

An instance variable belongs to one object. A class variable is stored on the class and is shared through it unless an instance attribute with the same name shadows it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
class User:
    role = "reader"          # class variable

    def __init__(self, name):
        self.name = name       # instance variable

ada = User("Ada")
grace = User("Grace")
print(ada.role)                # reader
User.role = "member"
print(grace.role)              # member

Mutable class attributes can accidentally share state:

class BadQueue:
    items = []                # one list shared by every instance

class Queue:
    def __init__(self):
        self.items = []       # a new list per instance

Use a class variable deliberately for genuinely shared configuration or counters. Put per-object mutable data in __init__.

Encapsulation: a clear interface, not absolute privacy

Encapsulation means presenting a comprehensible interface while keeping implementation details organized. Python does not enforce ordinary private instance variables. A leading underscore communicates that a name is non-public and should not normally be used by callers:

class Account:
    def __init__(self, balance):
        self._balance = balance

    def deposit(self, amount):
        if amount < 0:
            raise ValueError("amount must be non-negative")
        self._balance += amount

    @property
    def balance(self):
        return self._balance

Double-leading underscores trigger name mangling (for example, __token becomes a class-qualified name). This helps avoid accidental collisions in subclasses; it is not security or an access-control boundary.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Duck typing and polymorphism

Python often relies on behavior rather than a required concrete parent class. If a function needs an object with read(), it can accept any object that supplies that operation:

class MemorySource:
    def __init__(self, text):
        self.text = text

    def read(self):
        return self.text

class FileSource:
    def __init__(self, path):
        self.path = path

    def read(self):
        with open(self.path, encoding="utf-8") as file:
            return file.read()

def first_line(source):
    return source.read().splitlines()[0]

first_line depends on a small protocol: an object must provide a callable read() that returns text suitable for splitlines(). That behavioral contract is real even when no shared base class exists. Keep protocols small and document the operations callers rely on.

Composition versus inheritance

Composition gives an object collaborators or contained objects and delegates work to them—a “has-a” relationship. Inheritance creates a subtype—a deliberate “is-a” relationship that participates in the base type’s interface and method lookup.

Question Composition Inheritance
State ownership Each collaborator owns focused state. Base and subclass state are coupled through the hierarchy.
Substitutability Replace a collaborator that follows the needed protocol. Subclass should honor the base class’s promised behavior.
Extension Swap or add components at runtime. Override and extend inherited behavior.
Lookup and coupling Delegation is explicit; fewer inheritance rules. Method resolution and base-class changes affect subclasses.

A small composition example

class EmailSender:
    def send(self, address, message):
        print(f"Sending to {address}: {message}")

class Notifier:
    def __init__(self, sender):
        self.sender = sender

    def notify(self, address, message):
        self.sender.send(address, message)

Notifier has a sender. A test double or an SMS sender can replace EmailSender if it provides send(address, message).

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

When inheritance clarifies the model

class Shape:
    def area(self):
        raise NotImplementedError

class Rectangle(Shape):
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

Inheritance is appropriate when a rectangle genuinely satisfies the expectations of a shape and shares a meaningful interface. Do not choose it merely to reuse an unrelated implementation.

Overriding, super(), and method resolution order

A subclass can override an inherited method. super() calls the next implementation according to Python’s method resolution order (MRO):

class LoggedRectangle(Rectangle):
    def area(self):
        result = super().area()
        print(f"area={result}")
        return result

print(LoggedRectangle.__mro__)

Python linearizes lookup through inheritance, including diamond-shaped multiple-inheritance relationships, while preserving ordering constraints and avoiding repeated processing of a base class. Multiple inheritance is safest when every participating class uses the same cooperative super() pattern and accepts compatible arguments. Inspect ClassName.__mro__ when lookup is difficult to follow.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Special methods are language protocols

Special methods connect your objects to built-in operations and syntax. They are not arbitrary magic; each has an expected protocol.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
class Playlist:
    def __init__(self, songs):
        self.songs = list(songs)

    def __len__(self):
        return len(self.songs)

    def __iter__(self):
        return iter(self.songs)

    def __add__(self, other):
        return Playlist(self.songs + other.songs)

mix = Playlist(["A", "B"])
print(len(mix))
for song in mix:
    print(song)

Implement a special method when the operation naturally fits your type and its behavior is unsurprising. Otherwise, an ordinary method is clearer.

Dataclasses for record-like data

A dataclass remains a normal Python class, but generates common record support such as an initializer and representation:

from dataclasses import dataclass

@dataclass
class Point:
    x: float
    y: float

origin = Point(0, 0)
print(origin)  # Point(x=0, y=0)

Dataclasses are idiomatic for simple named data. Use ordinary methods or a regular class when the type must enforce invariants, coordinate collaborators, control mutation, or expose behavior beyond straightforward field storage.

When a function is better than a class

Do not wrap a one-off transformation in a class solely because OOP is being studied. A function and built-in structures are often easier to read, test, and reuse:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
def incomplete_titles(tasks):
    return [task["title"] for task in tasks if not task["completed"]]

tasks = [
    {"title": "Read", "completed": True},
    {"title": "Practice", "completed": False},
]

Choose a class when state has a clear owner, operations must protect invariants, or interchangeable implementations follow a useful protocol. Choose functions when data is simple and behavior does not need persistent identity.

A practical design checklist

  1. Identify state: What values exist, and which object owns each one?
  2. Locate behavior: Does an operation naturally belong with that state, or is a function more reusable?
  3. Define the contract: Which methods or special methods do callers actually need?
  4. Choose the relationship: Use composition for collaborators; use inheritance only for a genuine substitutable subtype.
  5. Pick the data shape: Use a dataclass for record-like named data; use a behavior-rich class for invariants and coordination.
  6. Check extension cost: Will delegation remain obvious, or will overrides and super() make lookup harder?
  7. Test boundaries: Verify invalid state, replacement collaborators, and any shared class state.

Practice exercise: model a library checkout

Start with a checkout workflow and decide deliberately:

  • Make a Book dataclass if it only stores title, author, and identifier.
  • Give a Member class behavior if it enforces borrowing limits.
  • Compose a checkout service with a catalog or notification collaborator.
  • Use a protocol-style requirement such as send(message) instead of demanding one notification implementation.
  • Reject inheritance unless one type is genuinely substitutable for another and the shared behavior remains clear.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.