Python Tutorials: Learn Python Polymorphism in Detail with Examples

Python Tutorials: Checkout the Detailed Explanation of Polymorphism in Python with Examples
Written by Paayi Tech |14-Sep-2020 | 0 Comments | 594 Views

Polymorphism is a technique by which we can change the attributes and normal functioning of the class. There are two types of polymorphism. Following are the names:

  • Method overloading
  • Method overriding

 

Method overriding:

Method overrides refer to making the same name method as defined in the parent class and changing the functionality of function. Sometimes we have to alter the functionality of the function that is given in a base class by default. OOP allows us to change the functionality by overriding the function. Consider the first example, which is the normal class, as we have studied earlier.

class MyClass(object):

    def __init__(self):

        self.value = 77

 

    def printValue(self):

        print(f"{self.value} from MyClass")

 

class ChildClass(MyClass):

    def __init__(self):

        super().__init__()

 

x = ChildClass()

x.printValue()

 

#Output

77 from MyClass

 

In the above example, when we create an object and try to get the value, it will return 77 as default. But what happens when we want to get the square value without making changes in the base class. Here comes the concept of method overriding. The above example is converted into polymorphism to apply the overriding function.

class MyClass(object):

    def __init__(self):

        self.value = 77

 

    def printValue(self):

        print(f"{self.value} from MyClass")

 

class ChildClass(MyClass):

    def __init__(self):

        super().__init__()

    def printValue(self):

        self.value = self.value ** 2

        print(f"{self.value} from ChildClass")

x = ChildClass()

x.printValue()

 

#Output

5929 from ChildClass

 

Method Overloading:

Unlike in C++ and Java, we cannot define multiple functions of the same in python method overloading. We have to do in a single function by using default values. These values are then executed if there are no such values given by the user.

Following is the example of method overloading in python

class MyClass(object):

    def hello(self,name = "Anonymous"):

        self.name = name

        print (f"Hello {self.name}")

 

obj = MyClass()

obj.hello()

obj.hello('Ash Ketchum')

 

#Output

Hello Anonymous

Hello Ash Ketchum

 

Similarly, we can make parameterized and non-parameterized constructor by the method overloading.

Now the classes end here. Do practice the classes and make your own program with the help of these helping code.

File Handling:

File handling is the most important part of storing data locally. Every time we cannot make a database on SQL or other services to store our data. Sometimes we store it locally in files. File handling is the easy and fastest way to store the data and fetching the data. File handling has four important functions which are as follows:

 

  • "r ": It reads the file and generates an error if the file is not found.
  • "w": It writes the file and creates the file if not present. Moreover, it will delete all the previous data if the file is present and write the new data.
  • "a": It appends the data in the already created file and not format the file as in the case of file writing. It will generate an error if no such file is found.
  • "x": It creates the file and returns an error if already exists.
  • "t": along with other functions, it will return text mode.
  • "b": along with other functions, it will return binary mode.

 

File Writing:

File writing is a process to write a file and add data to it. Following is the example of writing the file:

text='''Hello to python.

Today we are learning about file handling.

I am very much excited about this course.

I have covered some basics of python and moving toward advance slowly and gradually.

'''

 

filename = "demo.txt"

file = open(filename,"wt")

file.write(text)

 

file.close()

 

After running this program, the text data is store in demo.txt file, as shown in the image below:

Polymorphism in python tutorials

 

Reading The file:

We can also read the file from the interpreter by the following method:

filename = "demo.txt"

file = open(filename,"rt")

print(file.read())

 

file.close()

 

The output of the above code is as shown below:

#output:

Hello, to python.

Today we are learning about file handling.

I am very much excited about this course.

I have covered some basics of python and moving toward advance slowly and gradually.

 

 

Readlines:

readline() method returns all the line in a list which can be iterable. Following is the program to readlines:

filename = "demo.txt"

file = open(filename,"rt")

line = (file.readlines())

print (line)

for l in line:

    print(l)

file.close()

 

#Output

['Hello to python. ', 'Today we are learning about the file handling. ', 'I am very much excited about this course. ', 'I have covered some basics of python and moving toward advance slowly and gradually. ']

 

Hello, to python.

Today we are learning about file handling.

I am very much excited about this course.

I have covered some basics of python and moving toward advance slowly and gradually.

 

Appending Data in a File:

We can append the data in the already presented text file. Following is the example to add more data.

new_text='''Its a new text.

I am adding some more lines.

These lines don't make any sense.

Pikachu I choose you.'''

 

filename = "demo.txt"

file = open(filename,"at")

file.write(new_text)

file.close

 

Now we will see that if data is inserted or not. For this, we must read the file and see the data. The output after reading the file we get:

Hello, to python.

Today we are learning about file handling.

I am very much excited about this course.

I have covered some basics of python and moving toward advance slowly and gradually.

It's a new text.

I am adding some more lines.

These lines don't make any sense.

Pikachu, I choose you.

 

CSV writing:

CSV files are also called comma-separated files, are used as an alternative of excel sheets. It is extensively used in the process of data analysis. It is used to store data. The following is read and write operation on CSV file:

 

Write CSV:

import CSV

 

data = [['id','name'],['1','Pikachu'],['2','Blazikane']]

 

with open('pokemon.csv','w') as csv_file:

    writer = csv.writer(csv_file)

    writer.writerows(data)

csv_file.close()

 

Read Files:

import CSV

 

with open('pokemon.csv','r') as csv_file:

    reader = csv.reader(csv_file)

    print(list(reader))

csv_file.close()

 

 The output of the following code is :

[['id', 'name'], ['1', 'Pikachu'], ['2', 'Blazikane']]

With the help of the CSV file, we can do a lot of things. It is very easy to handle CSV files than a txt file when it comes to data analysis and maintaining it. We will do advanced work on CSV in our data analysis portion.





Login/Sign Up

Comments




Related Posts



© Copyright 2020, All Rights Reserved. paayi.com

This site uses cookies. By continuing to use this site or clicking "I Agree", you agree to the use of cookies. Read our cookies policy and privacy statement for more information.