Showing posts with label methods. Show all posts
Showing posts with label methods. Show all posts

Monday, March 15, 2021

Concept of Polymorphism in OOPS

 


Polymorphism


* The word "Polymorphism" comes from two Greek words "Poly" meaning "many" and "morphos" meaning "forms".

 

* Therefore , Polymorphism represents the ability to assume several different forms

 

* In Programming , if an object or a method is

exhibiting different form of behaviours , then the object is said to having polymorphic nature .

 

* Polymorphism provides flexibility in writing programs in such a way that the programmer uses same method call to perform different operations depending upon the requirement .

 

* Example Code for Polymorphism in Python :

 

- When a function can perform different tasks , then one can say that the function is exhibiting polymorphism behaviour .

 

- A simple example to write a function :

 

  def add(a,b):

       print(a+b)


* Since in Python , the variables are not declared explicitly , we are passing two variables 'a' and 'b' to the add() function where the variables are added to each other .

* CASE 01 - While calling the function , if we pass two integers like 5 and 15 to the function , then the function displays 15 as output .

 

* CASE 02 - If we pass two strings , then the same function concatenates or joins those strings . This means that the same function is adding two integers or concatenating two strings .

 

* Since the Polymorphism function is performing two different tasks , it is said to exhibit polymorphism behaviour .

 

* One can consider the following example for the case of Polymorphism :

=================================================

# Function that exhibits Polymorphism

def add(a,b):

    print(a+b)

 

# calling add() function and passing two integers

add(10,20)

 

# calling add() function and passing two strings

add("Core","Python"

 

 

* The Programming Languages which follow all the five features of OOPS – ( Classes with objects Abstraction , Encapsulation , Inheritance , Polymorphism) are called as object oriented programming languages .

 

* These type of behaviours are exhibited by C++ , Java and Python type of languages

Example of Inheritance Concept ( in OOPS ) in Python

 

 

Example of Inheritance in Python

 

* In Python lets assume that , one can take a class A with two variables 'a' and 'b' and a method like method01() in the given manner .

 

* Since all the methods are needed by another class B , one can extend class B from class A .

 

* If we want some additional members in object B , for example a variable 'c' and a method in the form of method02() . These methods are written in object B .

 

* From this one would remember that class B can use all the members of both A and B .

 

* This means that all the variables 'a' , 'b' , 'c' and the methods method01() and method02() are available to the class B . This means that all the members of class A are inherited by class B .

 

<< FIG >>

 

 

* By creating an object of B , one can access all the members of both the classes A and B that is when an object of class B is created which is a form of derived class object , from the base class , one can create another object .

 

Points to Remember on OOPS in Python

 

  Points to Remember on OOPS in Python

 

* Procedure oriented Programming Approach is the methodology where programming is done using procedures and functions .

 

* Procedure Oriented Programming Approach is generally followed by languages like C , Pascal and Fortran

 

* Python programming can take up programming using procedure oriented approach ( like C ) or Object Oriented Programming Approach ( like Java and C++ ) depending upon requirement .

 

* An object is anything that really exists in the world and can be distinguished from other objects . It is like an entity which has a unique existence and also displays some form of attributes and behaviours.

 

* Every Object has some behaviour that is characterised by attributes and actions . Here , attributes means the manner of conductance of any action . Attributes are represented by variables and actions are performed by methods . So , an object contains variables and methods .

 

* A function which is written inside a class is called as Method .

 

* A Class is a model or Blueprint for the creation of objects . And , a class contains variables and methods .

 

* Objects are created from a Class * An object does nothing without a class , however a class can exist without any object .

 

* Encapsulation is a mechanism where the data ( variables ) and the code ( methods ) that act on the data are bound together .

 

* Class is an example for Encapsulation since it contains both data and code .

 

* Hiding the unnecessary data and code from the user is called as Abstraction .

 

* In order to hide variables or methods , one should declare the variables or methods are private members . This is done by writing two underscores before the names of the variable or the methods .

 

* Private Members can be accessed using "Name Mangling" where the class name is used with single underscore before it and two underscores after it in the form of :

 

instancename._Classname_variable

instancename._Classname_method()

 

 

* Creating new classes from existing classes so that new classes would acquire all the features of the existing classes is called as Inheritance .

 

* In Inheritance , the first class generally created is called as Base Class or Super Class . The newly created Class is called as Sub-Class or Derived Class .

 

* Polymorphism represents the ability of an object or method to assume several different forms

 

* The Programming Languages which follow all the five features of OOPS namely : classes and objects , Encapsulation , Abstraction , Inheritance and Polymorphism are called as Object Oriented Programming Languages . For example: C++ , Java and Python fall into this category of Programming Languages .

 

Friday, March 12, 2021

Introductory Concept of Abstraction in Python


 

Introductory Concept of Abstraction in Python


* In languages like Java , there are several keywords like private , public and protected in order to implement the various levels of abstraction . These keywords are called as Access Specifiers .

* In Python , such kind of Access Specifiers are not available .

* Everything written inside the class comes under the category of public – that means all the objects , methods , variables present within any class in Python can be considered to be coming under Public Category which means that everything which is written inside a class is available outside the class to other people .

* Suppose , one does not want to make a variable outside the class or to other members inside the class , then we can write the variable with two double scores before it as : _var . This is like a private variable in Python .

* In the following example , 'y' is a private variable since it is written as : __y

class MyClass:

    def _init_(self):

        self.__y = 3

* Now , it is not possible to access the variables from within the class or outside of the class as :

m = MyClass()

print(m.y)

* The preceding print() statement displays an error message as : AttributeError :'MyClass' object has no attribute 'y' .


* Even though one can not access the private variable in this way .. however , it is possible to access it in the format :

instancename.__Classname_var


* This means that we are using the Classname differently to access the private variable . This concept is known as name mangling . In name mangling , one needs to use one underscore before the classname and two underscores after the classname . Like this , using the names differently to access the private variables is called as name mangling .

 * For example , in order to display a private variable 'y' value one can write the following code :

 print(m._MyClass_y)

The same statement can be written inside the method as :

print(self._MyClass_z) . When we use single underscore before a variable as _var , then that variable or object will not be imported into other files .

Thursday, March 11, 2021

Most Important Conceptual Problems Associated with Procedure Oriented Programming Approach and why OOPS was conceptualised

 


Problems in Procedure Oriented Approach


* In Procedure Oriented Programming Approach, the Programmer concentrates on a specific task and writes a set of functions to achieve the task.

 

* When there is another task to be added to the software, one should write another set of functions

 

* This means that the programmers concentration should be only on achieving the tasks.

 

* The Programmer perceives the entire system as fragments of several tasks. The Programmer perceives the entire system as fragments of several tasks.

 

* Whenever the Programmer wants to perform a new task , the Programmer would write a new set of functions . Therefore, there is no reusability of already existing code.

 

* A new task every time requires developing the code from the scratch . This is considered as a Waste of Programmer's time and effort .

 

* In Procedural Oriented Programming Approach, every task and sub- task is represented as a function and one function may depend on another function for accomplishment of a task or a set of related tasks which may be parallelly executed or serially executed.

 

* Therefore, when an error occurs over the software, the software needs examination of all the functions. Therefore, debugging or removing the errors is one of the most difficult operations to be performed. And as such, any updations to the software is very difficult to be achieved.

 

* When the software is developed, naturally the code size would also increase as the size of the code base increases .

 

* It has been observed in most of the software developed following the Procedure Oriented Approach that when the code size exceeds 10,000 lines and when it reaches 100,000 lines of code , then suddenly at a particular point , the programmers start losing control over the code .

 

* This means that , the programmers could not understand the exact behaviour of the code and could neither debug it nor extend it . This posed many problems , especially when the software was constructed to handle bigger and more complex systems .

 

* For example , in order to create software to send satellites into the sky and

Important Points to Remember : Dictionary Objects in Python ( syntax , usage , methods , behaviour etc )

 

  Points to Remember: Dictionary Objects in Python




 

1) A dictionary represents a group of elements arranged in the form of key-value pairs. In the dictionary object , the first element is considered as the 'key' and the immediate next element is considered as its associated 'value' .

 

2) The Key and Value Pairs should be written inside a dictionary by separating them with the help of a colon (:) operator. Each pair should be separated with the help of a comma sign. All the key-value pairs of the dictionary should be written inside curly braces { }

 

3) Indexing and Slicing are not useful to access the elements of a dictionary

 

4) While inserting a new element or modifying the existing element, it is preferable to use the given format:

 

dict(key) = Value

 

5) The keys of a dictionary should be unique and must be Immutable which means that once the data for the Keys is assigned, one cannot change the data type of the elements inside the dictionary.

 

6) The keys of a dictionary should be unique and belong to immutable datatype . The value associated with the key should be unique and should be immutable in nature.

 

7) The get(k,v) method returns the value upon taking the key 'k' . If the key is not found in the dictionary , then it will return a default value 'v'

 

8) The update({k:v}) method stores the key 'k' and its value 'v' pair into an existing dictionary

 

9) The dict() method converts a list or tuple or a zip object into a dictionary

 

10) The zip() method is useful to convert the sequences like lists into a zip class object

 

11) An ordered dictionary is a dictionary but it will keep the order of the elements

 

12) Ordered Dictionaries are created using the OrderedDict() method of collections module .

 

A descriptive article on - What are Ordered Dictionary Objects in Python and how to create them ( code over Jupyter Notebook IDE )

 



Ordered Dictionaries in Python


 

* The elements of a dictionary are not ordered . It means that the elements are not stored in the same order as they were entered into a dictionary

 

* For example , one can consider an employee database in a company which stores the employee details depending upon their seniority that is senior most employee's data may be inserted in the beginning of the database

 

* If the employee's details are stored in a dictionary , then the database will not show the employee details in the same order

 

* When the employee's details are changed , the seniority is disturbed and the data of the employee who joined the company first may not appear in the beginning of the dictionary .

 

* In such a case , the solution is to use ordered dictionaries .

 

* An Ordered Dictionary is a dictionary but it will keep the order of the elements in it . The elements are stored and maintained in the same order as they were entered into the ordered dictionary .

 

* One can create an ordered dictionary using the OrderedDict() method of the collections module . Therefore , we should import the method from the collections module as provided :

 

from collections import OrderedDict

 

Once the ordered dictionary item is created , one can assign an ordered dictionary with the name 'd' as given in the case :

 

d = OrderedDict()

 

One can store the key and values into the ordered dictionary 'd' as in the given manner :

 

d[10] = 'A'

d[11] = 'B'

d[12] = 'C'

d[13] = 'D'

 

Here , 10 is the identifier "Key" and its associated value is "A" . Therefore , the order is not disturbed as 'd' is the ordered dictionary . When we display the key-value pairs from the dictionary 'd' , we can see the same order .

 

=========================================

      Python Program to create a dictionary that

        does not change the order of Elements

=========================================

# create an ordered dictionary from

# collections import OrderedDict

 

d = OrderedDict()

d[10] = 'A'

d[11] = 'B'

d[12] = 'C'

d[13] = 'D'

# display the ordered Dictionary

for i , j in d.items():

    print(i,j)

 

Output

10 - A

11 - B

12 - C

13 - D




 

Friday, March 5, 2021

Dictionary Methods in Python for processing of constituent Key and Value Pair Data Objects

 

Dictionary Methods in Python


* There are various methods to process the elements of a dictionary

 * These methods are used for retrieving and manipulating the contents of a dictionary

 * These various methods have been summarised in the given description table


 ===================================

Methods to process Dictionaries in Python

===================================

 1) clear()

dict.clear()

This method removes all the key-value pairs from the dictionary 'd' .

 

2) copy()

d1 = dict.copy()

This method copies all the elements from the dictionary 'd' into a new dictionary object 'd1' .

 

3) fromkeys()

dict.fromkeys(s[,v])

This creates a new dictionary with keys from a given sequence 's' and all the values set to 'v'

 

4) get()

dict.get(k[,v])

This returns all the values associated with the key 'k' . If the key is not found , then it returns 'v'

 

5) items()

dict.items()

This returns an object that contains key-value pairs of dictionary item 'dict' . The key value pairs are stored as tuples in the objects .

 

6) keys()

dict.keys()

This returns a sequence of keys from the dictionary object "dict" .

 

7) values()

dict.values()

This returns a sequence of values from the dictionary object "dict"

 

8) update()

dict.update(x)

This method adds all elements from the dictionary 'x' to the dictionary item object 'dict'

 

9) pop()

dict.pop(k[,v])

This method removes the key 'k' and its associated value from the dictionary object "dict" and returns the value associated with that key "v" is returned . If the key is not found and "v" is not mentioned then "KeyError" exception error is raised .

 

10) setdefault()

dict.setdefault(k[,v])

If the key 'k' is found , then its value is returned and if the key is not found , then the k,v pair is stored into the dictionary 'd'. In the given program , we are going to retrieve the keys from a dictionary object using the keys() method . The keys() method returns dict_keys object that contains only keys . We will be also able to retrieve the values from the dictionary object using the values() method . This method "values()" returns all the values in the form of a dict_values object . Similarly , the items() method can be used to retrieve all the key-value pairs into the "dict_items"

method can be used to retrieve all the key-value pairs into the "dict_items" object .

 

==============================================

 

Program

A Python program to retrieve keys , values and key-value pairs from a dictionary object

# dictionary methods - create a dictionary with employee details

dict =

{

  'Name' : 'D001' ,

  'Id' : '001',

  'Salary' : 1000

}

 

# print the entire dictionary

print(dict)

# display only keys

print(" values in dict = ", dict.values())

# display both key and value pairs as tuples

print(" Items in Dictionary =", dict.items())

 

Output :

{

   'Name' : 'D001' ,

   'Id' : '001',

   'Salary' : 1000

}

Keys in dict =dict_keys(['Name','Id','Salary'])

Values in dict = dict_values(['D001','001','1000'])

Items in dict = dict_items([('Name','D001'),('Id',001),('Salary',1000)])

 

In the given program, we are creating a dictionary by entering the elements from the keyboard and when the user enters the elements from the keyboard inside the curly braces , then the values inside the dictionary object are treated as key value pairs of a dictionary by using the eval() function . Once the elements are entered , one can find the sum of the values using the sum() function over the values of the dictionary .


The screenshot for the used code implemented over Jupyter Notebook is given as below :