Object-Oriented Python3

Python is a fully object-oriented programming language but it can also be used for scripting. It is assumed that you are already familiar with object-orientation concepts and have experience writing object-oriented code in another language. This page will show how to write object-oriented code in Python without explaining object-oriented concepts.

The following class computes the area of a rectangle. Classes are defined with class keyword. init is the constructor. length and width are initialized in the constructor. Area is calculated by calcArea().

# class definition
class Rectangle():

   # constructor
    def __init__(self, length, width):
        self.length = length
        self.width = width

    # calculate area
    def calcArea(self):
        return self.length * self.width

# run the code
r = Rectangle(23, 32)
print(r.calcArea())       # output = 736

To use the class, we first create and object, r and then call r.calcArea() function.

Inheritance

Following example shows how to use inheritance in Python3.

class Vehicle():

    def __init__(self, make, model):
        self.make = make
        self.model = model

    def __str__(self):
        return self.make + " " + self.model

class Car(Vehicle):

    def __init__(self, make, model, wheels):
        Vehicle.__init__(self, make, model)
        self.wheels = wheels

    def __str__(self):
        return Vehicle.__str__(self) + " has " + self.wheels + " wheels"

v = Vehicle('Toyota','Corolla')
print(v)             
m = Car('Toyota','Corolla','four')
print(m)

output

Toyota Corolla
Toyota Corolla has four wheels

Vehicle is the base class. Car is the subclass. Note that declaration of the class Car takes superclass name as input parameter. Also note the use of Vehicle.init in Car class to initialize superclass variables and the use of Vehicle.str(self) in the str method to print values from superclass.

Polymorphism

Polymorphism basically refers to the same method call doing different things for different subclasses. In the following example, seats() method returns different results based on which subclass is called. The property name in the super class is used by all subclasses.

class Vehicle():
    def __init__(self, name):
        self.name = name

    # abstract method
    def seats(self):
        raise NotImplementedError("Subclass must implement abstract method")

class Sedan(Vehicle):
    def seats(self):
        return '4'

class Minivan(Vehicle):
    def seats(self):
        return '7'

class Motorbike(Vehicle):
    def seats(self):
        return '2'

vehicles = [Sedan('Tesla Model S'),
            Minivan('Toyota Sedona'),
            Motorbike('Harley Davidson')]

for vehicle in vehicles:
    print(vehicle.name + ' has ' + vehicle.seats() + ' seats')

output

Tesla Model S has 4 seats
Toyota Sedona has 7 seats
Harley Davidson has 2 seats