Object-Oriented Programming in Python for Data Science

Object-Oriented Programming in Python for Data Science

In this article, I am going to discuss Object-Oriented Programming in Python for Data Science with Examples. Please read our previous article where we discussed Regular Expressions and Packages in Python for Data Science with Examples. At the end of this article, you will understand the following pointers.

  1. Introduction to Python Classes
  2. Defining Classes
  3. Initializers
  4. Instance Methods
  5. Properties
  6. Class Methods and Data Static Methods
  7. Private Methods and Inheritance
  8. Module Aliases

Introduction to Python Classes

What is a Class?

A class is a user-defined blueprint or prototype used to build objects. Classes allow you to group data and functionality. Each instance of a class can have its attributes to keep track of its status. Class instances can additionally have methods for changing their state (specified by their class).

Consider the following scenario: you want to keep track of the number of cars with various attributes such as color, number of doors, model, and fuel type. Now, if you have to store these details for 100 different cars, that can be a difficult way to organize data.

A class creates a user-defined data structure with its data members and member methods that can be accessed and utilized by establishing a class instance. A class can be considered as an object’s blueprint.

What is an Object?

A collection of data (variables) and methods (functions) that act on that data is an object. We can make numerous objects from a class, just as we can make many vehicles from a car’s blueprint. An object is made up of the following elements:

  1. State – The characteristics of an object represent the state. It also reflects the attributes of an object.
  2. Behavior – The behavior of an object is represented by its methods. It can also be an object’s response to other objects.
  3. Identity – It gives a thing a unique name and allows it to communicate with other objects.

For example, we create an Object named SUV for a Class named car. Identity for this object will be – Eco Sport, state – color, fuel type; and behavior – drive.

Defining Classes in Python

Class definitions begin with the class keyword in Python, similar to how the function declarations begin with the def keyword. Consider this example of a simple class definition.

# Class creation
class Car:
  print("This is a sample class")

We’ve constructed a simple class that outputs a message in this example. To run a block of code within a class, we must first construct an object/instance. Here’s how to go about it.

# Class creation
class Car:
  print("This is a sample class")

# Object creation
SUV = Car()
Output –

Object-Oriented Programming in Python for Data Science with Examples

Initializers in Python

Every class should have a dedicated method called __init__. This is known as the initializer method. When a new instance of Point is created, this initializer method is automatically invoked. It allows the programmer to build up the appropriate attributes within the new instance by specifying their initial state/values.

The self-argument refers to the newly generated object that needs to be initialized or bind the arguments. An initializer method can be created by using the def keyword.

Syntax –

def __init__(self, argument):

     # body of the constructor

Example –
# Class creation
class Car:

  # Initializer Method
  def __init__(self):
    self.color = 'Black'
    self.fuel_type = 'Petrol'

# Object Creation
SUV = Car()

You can access these attributes by using the dot operator.

Example –
print("Details of the Car:")
# accees the values of initializer method
print(SUV.color, SUV.fuel_type)
Output –

Initializers in Python

Instance Methods in Python

The properties that are unique to each object are known as instance attributes. The instance attribute is duplicated in each item. Consider the class forms, which contain various objects such as circles, squares, and triangles, each with its properties and methods. For example, an instance attribute describes the properties of a specific object, such as the triangle’s edge being three and the square’s edge being 4.

An instance method has access to an instance’s attributes and can even modify its value. Only one default parameter exists – self. You can access the instance method by using object_name.method_name().

Example –
# Class creation
class Car:

  # Initializer Method
  def __init__(self):
    # Instance variables
    self.color = 'Black'
    self.fuel_type = 'Petrol'

  # Instance Method
  def car_color(self):
    # Updating the value of instance variable
    self.color = "Red"
    print("Colour of the car is", self.color)

# Object Creation
SUV = Car()
# Calling the instance method
SUV.car_color()
Output –

Instance Methods in Python

Class Methods and Data Static Methods in Python

In Python, a class method is a method that is bound to the class but not to its object. Although the static approaches are similar, there are a few key distinctions. Here are a few key points about the two methods.

Class Methods in Python
  • The initial argument for the class method is cls (class).
  • The class state can be accessed and modified by class methods.
  • The class method accepts the class as an argument and returns information about the state of the class.
  • @classmethod decorator is required for class methods
Static Methods in Python
  • There is no specified parameter for the static method.
  • The class state cannot be accessed or modified by a static method.
  • Static methods are unaware of class state. These methods take some parameters and do some utility functions.
  • @staticmethod decorator is required for static methods.

You can understand this concept better through this example –

# Class creation
class Car:

  # Initializer Method
  def __init__(self):
    # Instance variables
    self.color = 'Black'
    self.fuel_type = 'Petrol'

  # Creating a class method
  @classmethod
  def details(cls, color, fuel_type):
    print("This is a {} car of colour {}".format(fuel_type, color))

  # Creating a class method 
  @staticmethod
  def ecofriendly(fuel_type):
    if fuel_type.lower()=='electric':
      print("This car is ecofriendly!")
    else:
      print("This car is not ecofriendly!")

# Object Creation
SUV = Car()
SUV.details('Red', 'Electric')
SUV.ecofriendly('Electric')
Output –

Class Methods and Data Static Methods in Python

Private Methods and Inheritance in Python

Private Methods in Python-

Consider an automobile engine, which is made up of several parts such as a spark plug, valves, pistons, and so on. No one uses these parts directly; instead, they know how to use the parts that do. This is where private methods come in handy. It’s utilized to keep the inner workings of a class hidden from the outside world.

Private methods are those that should not be accessed outside of the class. Private methods, which can only be accessed within a class, do not exist in Python. To define a private method, add a double underscore “__” to the member name. If you try to access the private method outside the class, it will be an error.

To see how private methods, refer to this example –

# Class creation
class Car:

  # Public Method
  def car_color(self):
    print("This is a public method")

  # Private Method
  def __details(self):
    print("This is a private method")

  # Method to access the private method inside the class
  def run(self):
    self.car_color()
    self.__details()

# Object Creation
SUV = Car()
# access the methods
print("Accessing Public Method...")
SUV.car_color()
print("\nAccessing Methods inside class...")
SUV.run()
print("\nAccessing Private Method...")
SUV.__details()
Output –

Private Methods and Inheritance in Python

Inheritance in Python-

The capacity of one class to derive or inherit properties from another class is known as inheritance. It accurately depicts real-world relationships. It allows a code to be reused.

  1. The parent class, often known as the base class, is derived from the inherited class.
  2. A child class, often known as a derived class, is the one that inherits from another class.

This is how you can create a child class –

class child_class(parent_class):
       pass
Add a call to the parent’s __init__() function to retain the inheritance of the parent’s __init__() function.

Example –
# Parent Class
class Vehicle:

  def __init__(self):
    self.color = 'Black'

  def fuel_type(self):
    print("This is an Electric Vehicle")

# Child Class
class Bike(Vehicle):

  def __init__(self):
    # Inherit the initialiser method of the parent class
    Vehicle.__init__(self)
  
  # Method to use the attributes of parent class
  def details(self):
    print("The colour of this Bike is:", self.color)

# Object for child class
Superbike = Bike()
# Access the method of child class
Superbike.details()
Output –

Inheritance in Python

Python’s super() function allows a descendant class to inherit all of its parent’s methods and properties. You don’t have to use the parent element’s name when using the super() function because it will inherit the parent’s methods and attributes.

Example –
# Parent Class
class Vehicle:

  def __init__(self):
    self.color = 'Black'

  def fuel_type(self):
    print("This is an Electric Vehicle")

# Child Class
class Bike(Vehicle):

  def __init__(self):
    # Inherit the initializer method of parent class
    super().__init__()
  
  # Method to use the attributes of parent class
  def details(self):
    print("The color of this Bike is :", self.color)

# Object for child class
Superbike = Bike()
# Access the method of child class
Superbike.details()
Output –

Object-Oriented Programming in Python for Data Science with Examples

Module Aliases in Python

The as keyword in Python can be used to modify the names of modules and functions. You could want to give a new name to a module because you want to abbreviate a very long name you’ve been using a lot, or the same name is already being used somewhere in your program. The following is how this statement is put together:

import module_name as alias_name

Example –
import numpy as np

In the next article, I am going to discuss Debugging, Databases, and Project Skeletons in Python for Data Science with Examples. Here, in this article, I try to explain Object-Oriented Programming in Python for Data Science with Examples. I hope you enjoy this Object-Oriented Programming in Python for Data Science article.

Leave a Reply

Your email address will not be published. Required fields are marked *