본문으로 건너뛰기

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