Python / Python Object-Oriented Programming (OOP)

Introduction to Python OOP

In this introductory tutorial, you'll learn the basics of Object-Oriented Programming (OOP) in Python. This includes understanding concepts such as classes, objects, and methods.

Tutorial 1 of 5 5 resources in this section

Section overview

5 resources

Covers OOP concepts such as classes, objects, inheritance, and polymorphism.

Python OOP: An Introduction

1. Introduction

1.1 Goal of the tutorial

This tutorial aims to introduce you to the basics of Object-Oriented Programming (OOP) in Python. OOP is a programming paradigm that provides a means of structuring programs so that properties and behaviors are bundled into individual objects.

1.2 Learning outcomes

By the end of this tutorial, you'll be able to:
- Understand what OOP is
- Create classes and objects in Python
- Understand and implement methods in Python

1.3 Prerequisites

A basic understanding of Python is required to follow this tutorial.

2. Step-by-Step Guide

2.1 Classes and Objects

In Python, everything is an object. Objects in Python are created using classes. A class is like a blueprint for creating objects.

# Defining a class
class MyClass:
    x = 5

# Creating an object
p1 = MyClass()
print(p1.x)  # Output: 5

2.2 Methods

Methods are functions defined inside the body of a class. They are used to define the behaviors of an object.

# Defining a class with a method
class MyClass:
    def greet(self):
        print("Hello, world!")

# Creating an object and calling a method
p1 = MyClass()
p1.greet()  # Output: Hello, world!

In the example above, self is a reference to the current instance of the class, and is used to access variables that belong to the class.

3. Code Examples

3.1 Example 1: A Simple Class with a Method

class Dog:
    # Class attribute
    species = "Canis familiaris"

    # Instance method
    def __init__(self, name, age):
        self.name = name
        self.age = age

    # Another instance method
    def description(self):
        return f"{self.name} is {self.age} years old"

    # Another instance method
    def speak(self, sound):
        return f"{self.name} says {sound}"

# Instantiate the Dog object
miles = Dog("Miles", 4)

# Access the instance attributes
print(miles.name)  # Output: Miles
print(miles.age)   # Output: 4

# Call our instance methods
print(miles.description())  # Output: Miles is 4 years old
print(miles.speak("Woof Woof"))  # Output: Miles says Woof Woof

In this example, Dog is a class with two class attributes species, and four instance methods: __init__, description, and speak.

3.2 Example 2: Inheritance in Python

# Parent class
class Bird:
    def __init__(self):
        print("Bird is ready")

    def whoisThis(self):
        print("Bird")

    def swim(self):
        print("Swim faster")

# Child class
class Penguin(Bird):
    def __init__(self):
        super().__init__()
        print("Penguin is ready")

    def whoisThis(self):
        print("Penguin")

    def run(self):
        print("Run faster")

peggy = Penguin()  # Output: Bird is ready
                   #         Penguin is ready
peggy.whoisThis()  # Output: Penguin
peggy.swim()       # Output: Swim faster
peggy.run()        # Output: Run faster

In this example, Penguin is a subclass (or child class) of the Bird superclass (or parent class). The Penguin class inherits methods from the Bird class.

4. Summary

In this tutorial, you've learned about classes and objects in Python, how to define methods within a class, and how to apply inheritance in Python OOP.

5. Practice Exercises

5.1 Exercise 1

Create a Person class with name and age attributes, and a method greet that prints a greeting including their name.

5.2 Exercise 2

Create a Student class that inherits from the Person class, includes a grade attribute, and overrides the greet method to also include their grade in the greeting.

5.3 Exercise 3

Create an Employee class that also inherits from Person, includes a job attribute, and also overrides the greet method to include their job.

5.4 Solutions

# Solution to Exercise 1
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        print(f"Hello, my name is {self.name} and I'm {self.age} years old.")

# Solution for Exercise 2
class Student(Person):
    def __init__(self, name, age, grade):
        super().__init__(name, age)
        self.grade = grade

    def greet(self):
        print(f"Hello, my name is {self.name}, I'm {self.age} years old, and I'm in grade {self.grade}.")

# Solution for Exercise 3
class Employee(Person):
    def __init__(self, name, age, job):
        super().__init__(name, age)
        self.job = job

    def greet(self):
        print(f"Hello, my name is {self.name}, I'm {self.age} years old, and I'm a {self.job}.")

For further practice, try creating more complex classes that inherit from these, or adding more methods.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

CSS Minifier & Formatter

Clean and compress CSS files.

Use tool

WHOIS Lookup Tool

Get domain and IP details with WHOIS lookup.

Use tool

PDF Compressor

Reduce the size of PDF files without losing quality.

Use tool

AES Encryption/Decryption

Encrypt and decrypt text using AES encryption.

Use tool

File Size Checker

Check the size of uploaded files.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help