Object-Oriented Programming in Python: Use Classes

Organizing a Python program means deciding how to keep related data and the operations that use it together. Object-oriented programming (OOP) does this with classes, which define objects that hold data and provide operations on it.

I’ll show how to build a small class model and when a class fits a task better than a function.

TL;DR

Object-oriented programming groups state and behavior into classes, then uses instances to work with separate values.

  • Use a class when related operations need the same changing state.
  • Store per-object values on the instance and shared constants on the class.
  • Keep a short task without retained state as a function.

What Is Object-Oriented Programming in Python?

Object-oriented programming organizes code around objects that keep data and operations together. A class definition creates a class object that defines what its instances can do.

Because the example needed one caller for both item types, I ran python3 oop_demo.py. It printed one book summary and one audiobook summary.

TermMeaning
ClassA definition for attributes and methods available to its instances.
Instance or objectOne value created by calling a class.
AttributeData attached to a class or instance.
MethodA function defined on a class that can receive an instance.
EncapsulationKeeping related state and operations together.
AbstractionLetting callers use an operation without knowing its implementation.
InheritanceA child class starts with attributes and methods from a parent class.
PolymorphismDifferent object types respond to the same operation through their own implementations.

Python calls __new__ to create an instance. If that result belongs to the class, Python calls __init__ to initialize it. Custom __new__ methods mainly serve immutable types such as int and str.

A leading underscore on an attribute signals internal use by convention. It does not stop other code from accessing the attribute.

A built-in object can use methods without a custom class. A custom class can give a program-specific concept, such as Book, a named type.

How to Build a Small Python Class Model

Start with separate values on separate instances, then add related types that share an operation.

Step 1: Create instances with separate state

Book defines title and pages as instance attributes, which gives the later calls values to format.

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

    def summary(self):
        return f"{self.title}: {self.pages} pages"


first = Book("Python Basics", 280)
second = Book("Data Stories", 190)
print(first.summary())
print(second.summary())
Python Basics: 280 pages
Data Stories: 190 pages
Two Python Book instances print their own titles and page counts
Each call prints values stored on a separate Book instance.

I ran python3 instance_demo.py and saw each object print its own title and page count.

Step 2: Share an operation across related types

Python does not call a parent’s __init__ automatically when a child defines its own initializer. PrintBook and AudioBook use super().__init__(title) before assigning subtype fields. show_item stays outside the classes because it coordinates output rather than storing item state.

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

    def summary(self):
        return f"Item: {self.title}"


class PrintBook(LibraryItem):
    def __init__(self, title, pages):
        super().__init__(title)
        self.pages = pages

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


class AudioBook(LibraryItem):
    def __init__(self, title, minutes):
        super().__init__(title)
        self.minutes = minutes

    def summary(self):
        return f"Audio: {self.title} ({self.minutes} min)"


def show_item(item):
    print(item.summary())


items = [PrintBook("Python Basics", 280), AudioBook("Data Stories", 42)]
for item in items:
    show_item(item)
Book: Python Basics (280 pages)
Audio: Data Stories (42 min)
PrintBook and AudioBook outputs from a shared summary method
The same caller prints each item’s own summary.

isinstance(item, LibraryItem) also accepts child classes, while type(item) is LibraryItem checks for that exact class. Use the test that matches the kind of input the function accepts.

For a dog-park model, decide what the breed should change.

Dog designWhen it fitsWhat the caller does
One Dog class with a breed fieldThe breed labels the dog but does not change its behavior.Provide the breed value when creating the dog. Pass a sound to speak() when calling it.
Breed-specific child classA breed needs its own default for speak().Override speak() with the breed’s default sound, and allow callers to pass another sound when needed.
Child method calls super()The child wants to keep part of the parent method and extend it.Call the next implementation in Python’s method resolution order, then add the child behavior.

A Book can hold an Author object, which may exist independently and be linked to several Book instances, while PrintBook is a LibraryItem subclass that can be passed wherever that parent type is accepted. The inheritance guide and multiple inheritance article cover parent-child designs further.

Class Design Choices and Common Errors

Method binding and attribute lookup account for two common surprises in class code.

Fix a method that omits self

Python binds the instance when an instance method is retrieved, then supplies it as the first argument on the call.

class Book:
    def summary():
        return "A book"


book = Book()
try:
    print(book.summary())
except TypeError as error:
    print(f"{type(error).__name__}: {error}")
TypeError: Book.summary() takes 0 positional arguments but 1 was given
TypeError from calling a Python instance method without self
Captured TypeError from the method call.

I ran python3 missing_self_demo.py and saw the TypeError above. Add the conventional self parameter first so the method accepts its automatically bound instance.

A @staticmethod receives no implicit instance or class. A @classmethod receives the class as cls, so an alternate constructor can use cls(…) to create an instance of the class or its subclass.

Keep mutable instance data off the class

Run both versions and compare the printed lists after each owner adds a snack.

class SharedTray:
    snacks = []

    def __init__(self, owner):
        self.owner = owner

    def add(self, snack):
        self.snacks.append(snack)


morning = SharedTray("morning")
evening = SharedTray("evening")
morning.add("toast")
evening.add("pear")
print("shared:", morning.snacks, evening.snacks)


class PersonalTray:
    def __init__(self, owner):
        self.owner = owner
        self.snacks = []

    def add(self, snack):
        self.snacks.append(snack)


morning = PersonalTray("morning")
evening = PersonalTray("evening")
morning.add("toast")
evening.add("pear")
print("separate:", morning.snacks, evening.snacks)
shared: ['toast', 'pear'] ['toast', 'pear']
separate: ['toast'] ['pear']
Python class list shared between instances compared with separate instance lists
The two list locations produce different results.

I ran python3 shared_state_probe.py and got the lists shown above.

SharedTray.snacks is a class attribute, so both objects find the same list. PersonalTray creates a separate list on each instance, while assigning morning.snacks = [] would shadow the class attribute with an instance value.

A dataclass can generate __init__, __repr__, and __eq__ from annotated fields, with equality comparing same-type objects by those fields. Use field(default_factory=list) for a distinct list per object, or __post_init__ to derive values after initialization, as the dataclasses documentation explains.

ChooseWhen it fitsTrade-off
FunctionsA task transforms inputs or runs a fixed sequence without retaining state, such as formatting one report line.Pass values explicitly. A function may still accept an object as an argument without becoming its method.
Regular classSeveral operations use the same changing state, such as an order that moves from draft to paid.Adds a type to maintain, but methods can keep an order’s transition rules near its status.
DataclassAnnotated fields describe a record, such as application settings, and standard methods cover its needs.Less setup, with __post_init__ available to derive or check values after initialization.

For a plugin family with a required interface, abc.ABC and @abstractmethod can declare methods that each concrete child must implement. Python prevents instantiation while those abstract methods remain unimplemented. The standard library’s abstract base class guide describes this contract.

Conclusion

The Python class tutorial documents methods and inheritance in more detail. For instance attributes and method binding, see the data model. AskPython’s classes and objects guide adds another introductory example.

FAQ

These answers settle common questions about inheritance, method calls, and records.

Can I use classes without inheritance?

Yes. A class can group state and methods without defining a subclass. Inheritance is one way to specialize behavior, not a requirement for every class.

What does self receive in an instance method?

self receives the instance when Python binds an instance method. It is the conventional first parameter in the method definition.

What methods does @dataclass generate?

By default, @dataclass can generate __init__, __repr__, and __eq__ from the declared fields, unless the class already defines those methods.

Does Python require every program to define a class?

No. Built-in objects have methods, and a program can use them without declaring a custom class.

When does __init__ run?

Python calls __init__ to initialize a new instance after __new__ returns an instance of that class.

Does @dataclass validate annotated types?

No. Dataclasses use annotations to identify fields but generally do not enforce the annotated type at runtime. Add validation in application code when needed.

What does super() follow in multiple inheritance?

It follows the method resolution order, so the next implementation may come from a class other than the one named directly in your code.

Safa Mulani
Safa Mulani

An enthusiast in every forthcoming wonders!

Articles: 189