Object Oriented Programming Concepts in Python

Object-oriented programming (OOP) is a programming paradigm, that uses objects to represent data, functions, and operations.

Objects are instances of classes and can contain both data attributes and functions, which operate on the data.

When using an object-oriented approach, data and operations are typically organized into classes and organized into a hierarchical structure.

An example of OOP in Python is creating a class and defining functions to interact with the data within an instance of the class.

class Pet:
   def init(self, name):
      self.name = name
   def speak(self): 
      print("I'm %s, and I'm a pet!" % self.name)

p1 = Pet("Fido")
p1.speak()

Output: I’m Fido, and I’m a pet!

This code creates a class called Pet, which has two methods: init and speak.

The init method is a special method in Python classes that is automatically run when an instance of the class is created.

It is the first of the class methods that is called and provides the opportunity for the programmer to initialize any attributes of the object that are necessary or set up any initial state.

It is sometimes referred to as a “constructor” because it is responsible for initializing or constructing the object.

The init method takes in a parameter called name and assigns it to self.name.

The speak method prints out a statement which contains the self.name parameter.

After creating the class, an instance of Pet is created called p1 and the parameter “Fido” is passed into the init method.

Finally, the speak method is called on p1, which prints out “I’m Fido, and I’m a pet!”

Class Inheritance in Python

Inheritance is the process by which one class (called the subclass) can inherit the attributes and behaviors of another class (called the superclass).

Python supports multiple levels of inheritance, allowing subclass to inherit from as many super classes as needed.

For example, let’s create a wrapper class Animal that encapsulates common functionality related to animals, and then subclass it to create separate classes for each specific type of animal that you might want to represent:

class Animal:
   def init(self, name):
     self.name = name
   def move(self):
    print(f'{self.name} is moving')

class Cat(Animal):
   def meow(self):
     print(f'{self.name} is meowing')

class Dog(Animal):
   def bark(self):
     print(f'{self.name} is barking')

cat = Cat('Kitty')
dog = Dog('Fido')

cat.move() # 'Kitty is moving'
dog.move() # 'Fido is moving'

cat.meow() # 'Kitty is meowing'
dog.bark() # 'Fido is barking'

This code defines two classes, Animal and Cat and Dog.

The Animal class is a parent class which has the move() function.

The Cat and Dog classes are the subclasses of Animal class and have the meow() and bark() functions respectively.

We are then creating two objects of the Cat and Dog classes and calling each of the methods for each object.

For the Cat class, we call the move() and meow() methods and for the Dog class, we call the move() and bark() methods.

As a result, we get the corresponding output.

The print(f) function in Python is what is known as a formatting function.

It is used to insert objects into a string and allows for more control when printing strings.

It is similar to the older format function in Python, but provides more features and is more concise.

It allows for both positional and keyword arguments and can be used to properly format data into a predetermined string.

Data Abstraction in Python

Data abstraction is a concept in computer science that allows us to write code that is more concise and easier to understand, while still getting the same result.

It helps us to reduce complexity and focus on the essential parts of our program.

Data abstraction is useful because it allows us to give a name to a set of data and actions, so that we can refer to them without having to go into the details of each individual part.

In Python, data abstraction is achieved through the use of classes and objects.

A class is a blueprint for an object and it describes the properties, methods, and variables that are associated with the object.

An object is an instance of a class, and it can have its own values and methods that are defined by the class.

Data abstraction allows us to create objects that are more abstract and general, so that they can be used in more complex and diverse applications.

Data abstraction also helps developers write code that is more maintainable and reusable.

By writing code that can be broken down into smaller, separate parts, developers can use the code in multiple applications.

This means that when a change is necessary, only the specific parts of the code need to be updated, which reduces time and effort involved in making the changes.

Here is an example –

#abstraction is the process of taking out of data from a larger data set and #using only the required information

#example code:

#creating a class to store dataset

class DataSet:
   def init(self, data):
     self.data = data

#abstaining data
   def abstain(self, index):
     return self.data[:index]

#Creating an instance of DataSet class

my_data = DataSet([1, 2, 3, 4, 5, 6])

#Printing the first 3 elements

print(my_data.abstain(3)) # Output: [1, 2, 3]

In this example, a class named DataSet is created with an initializer method that takes a parameter ‘data’.

The function ‘abstain’ is then defined which takes an index parameter and returns the elements from self.data[:index].

A DataSet instance is then created with an array of data and the ‘abstain’ function is used to print the first 3 elements of the data.

In this case, the data elements are kept hidden and the user is only presented with a function to access the data.

Polymorphic Data Models

Python allows for polymorphic data models, which allow the same data to be used in multiple data structures.

This feature allows developers to take advantage of the advantages of different types of data structures while still working with familiar data.

Polymorphic data models are utilized in object-oriented programming, which is widely used in Python.

Polymorphic data models allow developers to define classes that contain different types of data, such as strings, integers, floats, and lists.

These data classes can be manipulated and experimented with in different ways as needed.

With a polymorphic data model, objects of different classes can be used in the same code, allowing for more flexibility and code reuse.

For example, a list of strings can be combined with a range of integers to create a list of integrals.

Similarly, a string can be added to a dictionary to create a new dictionary composed of both strings and integers.

This can be done easily with the use of data classes, eliminating the need for additional code.

Polymorphic data models are also useful when it comes to database programming.

This is because database objects can be used in many ways no matter what data structure is utilized.

For instance, database objects can be used for sorting and searching, regardless of the database structure.

Taking full advantage of polymorphic data models allow developers to access and manipulate database objects with ease.

Example of polymorphic data models –

class Animal:
   def init(self, sound, color):
     self.sound = sound
     self.color = color
   def make_sound(self):
     print(self.sound)

class Cat(Animal):
   legs = 4 
   def purr(self):
     print("Purr purr …")

class Dog(Animal):
   legs = 4
   def bark(self):
     print("Woof woof !")

cat = Cat('meow', 'black')
dog = Dog('bark', 'brown')

cat.make_sound()
dog.make_sound()

cat.purr()
dog.bark()

This code is creating a Polymorphic Data Model in Python.

This model has a base class of Animal, with the class constructor taking two arguments for sound and color.

There is then a Cat and a Dog subclass, both with the same legs argument.

The make_sound, purr and bark functions demonstrate polymorphism as all of them can be called from either the Animal or subclass instances.

This code creates a Cat and a Dog instances then uses the functions to print out their sounds and the Cat’s purring.

Encapsulation in Python

In Python, encapsulation is a way of limiting direct access to certain components or methods of a class by the programmer.

This means that the programmer can only access certain data or functionality of a class by using the methods and properties that are available for it.

By using encapsulation, the programmer can protect their code from changes even from other modules in the same program.

This prevents accidental or malicious data alterations from happening in the code while also allowing for code reuse.

Encapsulation in Python can be implemented by using the private variables and by using classes.

Private variables in Python can be declared by adding two underscores at the start of a variable, like self.__variable. This can be used to restrict the access of variables from outside and the user cannot modify it.

Further, classes can be used to implement encapsulation in Python.

By using classes, we can create objects and all the data associated with that particular object can be kept in the object and it can be hidden from other objects.

This process helps in restricting the direct access to the attributes present in the object.

Here is a sample code demonstrating Encapsulation in Python:

class Encapsulate:
   def init(self):
     self.a = "Private"
     self._b = "Protected"
     self.__c = "Public"
   def __method(self): 
     print("This is a private method") 

   def method(self): 
     print("This is a public method") 

   def get_c(self): 
     return self.__c 

obj = Encapsulate()

#Private member can not be accessed

print(obj.a)

#Protected member can be accessed

print(obj._b)

#Private member name is mangled

print(obj._Encapsulate__c)

#Calling public method

obj.method()

#Calling private method

#obj._Encapsulate__method()

This Python code defines a class called “Encapsulate“; this class has three attributes (a, _b, and __c) and two methods (__method and method).

The a attribute is a private attribute and cannot be accessed directly.

The _b attribute is a protected attribute and can be accessed directly but should not be modified.

The __c attribute is a public attribute and it can be accessed directly.

The __method and method methods are private and public methods, respectively, and can be called on an instance of the Encapsulate class.

The get_c method can be used to access the __c attribute.

Interfaces in Python

Interfaces in Python are abstract classes with named collections of methods that describe the behavior of a class without actually providing any implementations.

By conforming to the interface, a class is able to receive and interact with other classes that also conform to the interface.

This allows for complex systems to be built from classes that can act as components within the larger system.

Interfaces in Python are implemented using protocols – collections of methods defined which enable objects from different classes to interact with each other.

Once an interface is declared, one or more classes can inherit from it and implement its behaviours.

Example #1: A Simple Interface

class IExampleInterface:
   def hello_world(self): 
     pass

class ExampleImplementation(IExampleInterface):
   def hello_world(self): 
     print('Hello World!')

x = ExampleImplementation()
x.hello_world()

#Output:
Hello World!

This example creates a class, IExampleInterface, which defines an interface with a single method, hello_world().

It also creates a subclass, ExampleImplementation, which implements the hello_world() method and prints “Hello World!” to the console.

Finally, an object of type ExampleImplementation is created and its hello_world() method is called, causing the “Hello World!” message to be printed.

Leave a Reply

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

*