English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python Basic Tutorial

Python Flow Control

Python Functions

Python Data Types

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced Python Knowledge

Python Reference Manual

Python Object-Oriented Programming

In this article, you will learn about object-oriented programming (OOP) in Python and its basic concepts through examples.

Python OOP Introduction

Python is a multiparadigm programming language. This means that it supports different programming methods.

One popular method to solve programming problems is to create objects. This is also known as Object-Oriented Programming (OOP).

An object has two features:

  • Property

  • Behavior

Let's take an example:

A parrot is an object,

  • Name, age, color are properties

  • Singing and dancing are behaviors

The concept of OOP in Python focuses on creating reusable code. This concept is also known as DRY (Don't Repeat Yourself) - Do Not Repeat Yourself.

In Python, the concept of OOP follows some basic principles:

InheritanceThe process of using the details of a new class without modifying the existing class.
Encapsulation

Hiding the private details of the class from other objects.

Polymorphism

The concept of using universal operations in different ways for different data inputs.

Class (class)

A class is the blueprint of an object.

We can consider a class as a sketch of a parrot with labels. It contains all the details such as name, color, size, etc. Based on these descriptions, we can study the parrot. Here, the parrot is an object.

An example of the parrot class can be:

class Parrot:
    pass

Here, we use the class keyword to define an empty class Parrot. We construct an example from the class. An example is a specific object created by a specific class.

Object (Object)

An object (example) is an instance of a class. When defining a class, only the description of the object is defined. Therefore, no memory or storage is allocated.

An example of a parrot class object can be:

obj = Parrot()

Here, obj is an object of the Parrot class.

Assuming we have the details of a parrot. Below, we will demonstrate how to build a class and object for a parrot.

Example1: Creating classes and objects in Python

class Parrot:
    # Class attributes
    species = "bird"
    # Example attributes
    def __init__(self, name, age):
        self.name = name
        self.age = age
# 示例化Parrot类
# Example instances of Parrot class 10)
blu = Parrot("麻雀", 15)
woo = Parrot("鹦鹉",
# Access class attributes
print("The sparrow is {}".format(blu.__class__.species))
print("The parrot is also {}".format(woo.__class__.species))
# Access instance attributes
print("{} has {} years old".format(blu.name, blu.age))

When we run the program, the output will be:

print("{} has {} years old".format(woo.name, woo.age))
The sparrow is a bird
The parrot is also a bird 10 The parrot has
The sparrow has 15 The parrot has

years oldParrotIn the above program, we create a class named

the class. Then, we define properties. Properties are the characteristics of objects.Parrotwe createbluandClass instances. Here,woo

is a reference (value) to our new object.

Then, we use class .species to access class attributes. The class attributes of all instances of a class are the same. Similarly, we use blu.name and blu.age to access instance attributes. However, for each instance of the class, the instance attributes are different.To learn more about classes and objects, please go to

Python classes and objects.

Methods

Example2: Methods are defined within the class body. They are used to define the behavior of objects.

class Parrot:
    
    # Example attributes
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    # Example method
    def sing(self, song):
        return "{} sings {}".format(self.name, song)
    def dance(self):
        return "{} is now dancing".format(self.name)
# Example object
blu = Parrot("Blu", 10)
# Call our example methods
print(blu.sing("'Happy'"))
print(blu.dance())

When we run the program, the output will be:

Blu sings 'Happy'
Blu is now dancing

In the above program, we define two methods, namely sing() and dance(). These are called example methods because they are called on the example object (i.e., blu).

Inheritance

Inheritance is a method of creating a new class to use it without modifying the details of the existing class. The newly formed class is a derived class (or subclass). Similarly, the existing class is a base class (or parent class).

Example3:Inheritance in Python

# Base class
class Bird:
    
    def __init__(self):
        print("Bird is ready")
    def whoisThis(self):
        print("Bird")
    def swim(self):
        print("swims faster")
# Subclass
class Penguin(Bird):
    def __init__(self):
        # call super() function
        super().__init__()
        print("Penguin is ready")
    def whoisThis(self):
        print("Penguin")
    def run(self):
        print("runs faster")
peggy = Penguin()
peggy.whoisThis()
peggy.swim()
peggy.run()

When we run the program, the output will be:

Bird is ready
Penguin is ready
Penguin
swims faster
runs faster

In the above program, we created two classes, namelyBird(父类)andPenguin(子类)。Subclasses inherit the functionality of the parent class. We can see this from the swim() method. The subclass again modifies the behavior of the parent class. We can see this from the whoisThis() method. In addition, we extend the functionality of the parent class by creating a new run() method.

Additionally, we use the super() function before the init() method. This is because we want to pull the content of the init() method from the parent class to the subclass.

Encapsulation

In Python, using OOP, we can limit access to methods and variables. This can prevent direct modification of data (known as encapsulation). In Python, we use an underscore as a prefix to indicate private attributes, i.e., single "_" or double "__".

Example4:Encapsulation in Python

class Computer:
    def __init__(self):
        self.__maxprice = 900
    def sell(self):
        print("Price: {}".format(self.__maxprice))
    def setMaxPrice(self, price):
        self.__maxprice = price
c = Computer()
c.sell()
# Change the price
c.__maxprice = 1000
c.sell()
# Use setter function
c.setMaxPrice(1000)
c.sell()

When we run the program, the output will be:

Selling price: 900
Selling price: 900
Selling price: 1000

In the above program, we definedComputerClass. We use the __init__() method to store the highest selling price of the computer. We try to modify the price. But we can't change it because Python will__maxpriceConsidered as private attributes. To change the value, we use the setter function, that is, setMaxPrice(), which takes price as a parameter.

Polymorphism

Polymorphism is a feature (in OOP) that can use a common interface for multiple forms (data types).

Suppose we need to color a shape, and there are multiple shape options (rectangle, square, circle). However, we can use the same method to color any shape. This concept is called polymorphism.

Example5:Using polymorphism in Python

class Parrot:
    def fly(self):
        print("Parrots can fly")
    
    def swim(self):
        print("Parrots cannot swim")
class Penguin:
    def fly(self):
        print("Penguins cannot fly")
    
    def swim(self):
        print("Penguins can swim")
# Universal interface
def flying_test(bird):
    bird.fly()
# Example object
blu = Parrot()
peggy = Penguin()
# Pass the object
flying_test(blu)
flying_test(peggy)

When we run the above program, the output will be:

Parrots can fly
Penguins cannot fly

In the above program, we defined two classesParrotandPenguin. Each of them has a universal fly() method. However, they have different functions. To allow polymorphism, we created a universal interface, that is, the flying_test() function can accept any object function. Then, we passedbluandpeggyObject, it runs effectively.

Key points of object-oriented programming:

  • Make programming simple and effective.

  • Classes are shareable, so code can be reused.

  • Improve the productivity of programmers

  • Data is safe through data abstraction.