メインコンテンツにスキップ

Object-Oriented Programming in Python: A Complete Guide

Learn the basics of object-oriented programming in Python: classes, objects, attributes, and methods explained step by step with code examples.
· 12 分 読む

AIで探求

Object-Oriented programming (OOP) is a widely used concept to write applications. As a data scientist, you should be able to write applications to process your data, among a range of other things.

In this tutorial, I cover the basics of object-oriented programming in Python. You will learn how to create a class and instantiate objects, how to define methods and pass arguments to it, and how to add attributes to a class.

TL;DR

  • OOP organizes code around classes (blueprints) and objects (instances of those blueprints)

  • Define a class with the class keyword and initialize attributes inside __init__(self)

  • Instance methods operate on object data via self and are called with dot notation: my_object.method()

  • Python supports all four OOP pillars: encapsulation, inheritance, polymorphism, and abstraction

  • OOP promotes code reuse to create multiple objects from a single class template

What Is OOP?

Object-oriented programming (OOP) is based on the imperative programming paradigm, which uses statements to change a program's state. Imperative means that it focuses on describing how a program should operate. Examples of imperative programming languages are C, C++, Java, Go, Ruby and Python.

This stands in contrast to declarative programming, which focuses on what the computer program should accomplish, without specifying how (e.g., SQL, XQuery). For a comparison of paradigms, see our guide to functional programming vs. OOP.

OOP uses the concept of objects and classes. A class can be thought of as a 'blueprint' for objects. These can have their own

  • Attributes: characteristics they possess
  • Methods: actions they perform

OOP has a few key advantages over other design patterns. Development is often faster and cheaper, and the modular approach makes software easier to maintain. This, in turn, leads to higher-quality software, which is also extensible with new methods and attributes.

The learning curve is, however, longer. The core concepts require more upfront investment to understandfully. Computationally, OOP software is slower, and uses more memory since more lines of code have to be written.

The Four Pillars of OOP

Beyond classes and methods, OOP rests on four pillars that I have only touched on lightly so far. Each one deserves its own deep dive, but here is a quick overview with links to dedicated tutorials.

PillarWhat it meansLearn more
EncapsulationBundling data and methods together, controlling access with naming conventions (_private, __name_mangled)Encapsulation in Python
InheritanceCreating child classes that reuse and extend parent class behaviorPython Inheritance
PolymorphismDifferent classes sharing the same interface, so code can work with objects interchangeablyOOP in Python course
AbstractionHiding complexity behind a clean interface using abstract base classesPython Abstract Classes

OOP Example

An example of a class is the class Dog. Don't think of it as a specific dog, or your own dog. We're describing what a dog is and can do, in general. Dogs usually have a name and age; these are instance attributes. Dogs can also bark; this is a method.

When you talk about a specific dog, you would have an object in programming: an object is an instantiation of a class. This is the basic principle on which object-oriented programming is based. So my dog Ozzy, for example, belongs to the class Dog. His attributes are name = 'Ozzy' and age = '2'. A different dog will have different attributes.

OOP in Python

Python is one of the most popular languages for learning and applying OOP. Below, I cover what makes Python well-suited for object-oriented code and walk through the core syntax.

Is Python object oriented?

Python is a great programming language that supports OOP. You will use it to define a class with attributes and methods, which you will then call.

Python's key advantage over other programming languages like Java, C++ or R is that it is a dynamic language with high-level data types. This means it does not require the programmer to declare types of variables and arguments, which makes development much faster and code more readable than with Java or C++.

If you're new to Python, be sure to take a look at our Introduction to Python course.

How to create a class

To define a class in Python, you can use the class keyword, followed by the class name and a colon.

Inside the class, an __init__ method (a dunder method) is typically defined with def. This is the initializer that you can later use to instantiate objects. It's similar to a constructor in Java.

__init__ is called automatically when you create a new object. It takes one argument: self, which refers to the object itself.

Inside the method, the pass keyword is used as of now, because Python expects you to type something there. Remember to use correct indentation!

class Dog:

    def __init__(self):
        pass

Note: self in Python is equivalent to this in C++ or Java.

In this case, you have a (mostly empty) Dog class, but no object yet. Let's create one!

Instantiating objects

To instantiate an object, type the class name, followed by two brackets. You can assign this to a variable to keep track of the object.

ozzy = Dog()

And print it:

print(ozzy)
<__main__.Dog object at 0x111f47278>

Adding attributes to a class

After printing ozzy, it is clear that this object is a dog. But you haven't added any attributes yet. Let's give the Dog class a name and age by rewriting it:

class Dog:

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

You can see that the function now takes two arguments after self: name and age. These then get assigned to self.name and self.age respectively. You can now create a new ozzy object with a name and age:

ozzy = Dog("Ozzy", 2)

To access an object's attributes in Python, you can use the dot notation. This is done by typing the name of the object, followed by a dot and the attribute's name

print(ozzy.name)

print(ozzy.age)
Ozzy
2