Thursday, November 29, 2018

Pickling and unpickling

Pickling 

In order to store complex information such as list and dictionary Python's pickle module is used as text files are limited to storing a series of characters. Once written as a text file, it is a simple text file, meaning next time you read it in you will have parse the text and process it back to your original data structure. 

What you want, then, is a way to save your Python data object as itself, so that next time you need it you can simply load it up and get your original object back. Pickling and unpickling let you do that. A Python data object can be "pickled" as itself, which then can be directly loaded ("unpickled") as such at a later point; the process is also known as "object serialization". 

Let's see an example:


import pickle
names = ["Vivek","Satya", "Nagaraju"]
skillset = ["Python", "C#", "PHP"]
pickle_file = open('employees.dat','wb')
pickle.dump(names,pickle_file)
pickle.dump(skillset,pickle_file)
pickle_file.close()



The names and skillset are two lists which we have to store. 
The pickle_file = open("employees.dat","w") syntax creates a pickle_file object in write binary mode. The pickle.dump() is used to dump and store the lists names and skillset in the employees.dat file. The pickle.dump() requires two arguments, first the data (like list) to pickle and second the file to store it. The pickle_file.close() finally close the file.

Open the employees.dat file to see the content, which in my case is:
 
€ ]q (X    Vivekq X    Satyaq X    Nagarajuq e.€ ]q (X    Pythonq X    C#q X    PHPq e.

Need for pickling

It is very useful when you want to dump some object while coding in the python shell. So after dumping whenever you restart the python shell you can import the pickled object and de-serialize it. Some other uses are:

1) saving a program's state data to disk so that it can carry on where it left off when restarted (persistence)

2) sending python data over a TCP connection in a multi-core or distributed system (marshalling)

3) storing python objects in a database

4) converting an arbitrary python object to a string so that it can be used as a dictionary key (e.g. for caching & memoization).


Unpickling

Unpickling means retrieving the data from the pickle file. In the previous topic, you learned how to store (list, dictionary) data in the pickle file; now it's time to retrieve the stored data. In order to perform unpickling, we will use pickle.load(). The pickle.load() takes one file object as an argument. Let's see an example:

import pickle
pickle_file = open("employees.dat",'rb')
names_list = pickle.load(pickle_file)
skillset_list =pickle.load(pickle_file)
print (names_list ,"and", skillset_list)

The pickle_file = open("employees.dat",'rb') syntax creates a file object in read mode. The names_list = pickle.load(pickle_file) syntax reads the first pickled object in the file and unpickles it. Similarly, skillset_list =pickle.load(pickle_file) reads the second pickled object in the file and unpickles it.

The output of this program is:

['Vivek', 'Satya', 'Nagaraju'] and ['Python', 'C#', 'PHP']


In pickle, you can not access the data randomly. Pickle stores and retrieves the list
sequentially. The data you dump in the pickle file first, would be retrieved first. This is the limitation of the pickle file.

Given the limitation of the pickle file, you can't access the list randomly, but you can use the dictionary with lists to retrieve the lists randomly.

Let's see this through an example:

import pickle

pickle_file = open('employees1.dat','wb')

emp_dict = {
'names' : ["Vivek","Satya", "Nagaraju"],
'skillset' : ["Python", "C#", "PHP"]
            }

pickle.dump(emp_dict,pickle_file)

pickle_file.close()

Through this program we have dumped a dictionary referred by name emp_dict . When we run the preceding program and check the directory. A file named employees1.dat must be created. If I open this file its content is:

€ }q (X    namesq ]q (X    Vivekq X    Satyaq X    Nagarajuq eX    skillsetq ]q (X    Pythonq X    C#q    X    PHPqeu.

It's time to unpickle and retrieve the content of the employees1.dat file. See the program below:

import pickle
pickle_file = open("employees1.dat",'rb')
emp_data = pickle.load(pickle_file)
print(emp_data["skillset"])
print(emp_data["names"])

 

In the preceding program, emp_data is the dictionary and we are accessing the values of the dictionary by keys. The output of the program will be:

['Python', 'C#', 'PHP']
['Vivek', 'Satya', 'Nagaraju']



Here our discussion comes to end. Next post will be on Exception handling which is another important concept. Till we meet next, keep practicing and learning Python as Python is easy to learn!







 



Share:

Wednesday, November 28, 2018

The os.path module

The os.path module contains many helpful functions related to filenames and file paths. Since os.path is a module inside the os module, you can import it by simply running import os. Lets us look at some some methods in the os.path module.

1. os.path.join()

If we pass it the string values of individual file and folder names in our path, os.path.join() will return a string with a file path using the correct path separators. Enter the following into the interactive shell:

import os
os.path.join('Python_Code','examples','MyCode')

The output you'll see is: 

'Python_Code\\examples\\MyCode'

Since I'm running these interactive shell examples on Windows, so os.path.join('Python_Code','examples','MyCode') returned 'Python_Code\\examples\\MyCode'. The backslashes are doubled because each backslash needs to be escaped by another backslash character.

The os.path.join() function is helpful if you need to create strings for filenames. For example, the following example joins names from a list of filenames to the end of a folder’s name:

import os

file_list = ['euler.txt','newcities.txt','m2.jpg']

for file_name in file_list:
   

    print(os.path.join('F:\\Text_files',file_name))



The output of the program will be:

F:\Text_files\euler.txt
F:\Text_files\newcities.txt
F:\Text_files\m2.jpg


2. Functions for current working directory

We can get the current working directory as a string value with the os.getcwd() function and change
it with os.chdir().

Enter the following into the interactive shell:

>>> import os
>>> os.getcwd()


I output I got is 'C:\\Users\\Python'. If I want to change my current working directory to F:\Text_files I'll use the os.chdir() as follows:

os.chdir('F:\\Text_files')

Now if I run  >>> os.getcwd() my output will be:

'F:\\Text_files'

 
 3. Handling Absolute and Relative Paths

In the  os.path module there are functions for returning the absolute path of a relative path and for checking whether a given path is an absolute path. An absolute path, which always begins with the root folder. A relative path, which is relative to the program’s current working directory. There are also the dot (.) and dot-dot (..) folders. These are not real folders but special names that can be used in a path. A single period (“dot”) for a folder name is shorthand for “this directory.” Two periods (“dot-dot”) means “the parent folder.”

a. Calling os.path.abspath(path) will return a string of the absolute path of the argument. This is an easy way to convert a relative path into an absolute one. So if I type:

>>> os.path.abspath('.')

The output is:

'C:\\Users\\Python'


b. Calling os.path.isabs(path) will return True if the argument is an absolute path and False if it is a relative path. So if I type:

>>> os.path.isabs('.')

I get the output False. However this input gives true:

>>> os.path.isabs(os.path.abspath('.'))
True


c. Calling os.path.relpath(path, start) will return a string of a relative path from the start path to path. If start is not provided, the current working directory is used as the start path. So if I type:

>>> os.path.relpath('\Python')
'..\\..\\Python'
 

>>> os.path.relpath('C:\\Users','C:\\')
'Users' 

Two periods (“dot-dot”) means “the parent folder.”

 d. The os.path.dirname(path) will return a string of everything that comes before the last slash in the path argument. Calling os.path.basename(path) will return a string of everything that comes after the last slash in the path argument. Enter the following into the interactive shell:

>>> path = 'C:\\Users\\Python\\calc.exe'
>>> os.path.basename(path)

'calc.exe'

>>> os.path.dirname(path)
'C:\\Users\\Python'

If we need a path’s dir name and base name together, you can just call os.path.split() to get a tuple value with these two strings, like so:

>>> myFilePath = 'C:\\Users\\Python\\calc.exe'
>>> os.path.split(myFilePath)

('C:\\Users\\Python', 'calc.exe')


The os.path.split() does not take a file path and return a list of strings of each folder. For that, use the split() string method and split on the string in os.sep variable which is set to the correct folder-separating slash for the computer running the program. For example, enter the following into the interactive shell:

>>>myFilePath.split(os.path.sep)

['C:', 'Users', 'Python', 'calc.exe']


4.Finding File Sizes and Folder Contents

The os.path module provides functions for finding the size of a file in bytes and the files and folders
inside a given folder.

a. Calling os.path.getsize(path) will return the size in bytes of the file in the path argument. For example:

>>> os.path.getsize('C:\\Users\\Python\\calc.exe')

776192

b. Calling os.listdir(path) will return a list of filename strings for each file in the path argument. But this function is in the os module, not os.path. For example:

>>> os.listdir('C:\\Users\\Python\\calc.exe')

['0409', '12520437.cpx', '12520850.cpx', '5U877.ax', 'aaclient.dll',
--snip--
'xwtpdui.dll', 'xwtpw32.dll', 'zh-CN', 'zh-HK', 'zh-TW', 'zipfldr.dll']


If I want to find the total size of all the files in a directory, I can use os.path.getsize() and os.listdir() together. For example:

dirSize = 0

for file_name in os.listdir(
'C:\\Users\\Python'):


    dirSize = dirSize + os.path.getsize(os.path.join('C:\\Users\\Python\\, file_name))

print(dirSize )

The output of this program is:

1117846456

As we loop over each file_name in the C:\\Users\\Python folder, the dirSize variable is incremented by the size of each file. Notice how when I call os.path.getsize(), I use os.path.join() to join the folder name with the current filename. The integer that os.path.getsize() returns is added to the value of dirSize. After looping through all the files, I print dirSize to see the total size of the C:\\Users\\Python folder.

5. Checking Path Validity

The os.path module provides functions to check whether a given path exists and whether it is a file or folder.

• Calling os.path.exists(path) will return True if the file or folder referred to in the argument exists and will return False if it does not exist.

• Calling os.path.isfile(path) will return True if the path argument exists and is a file and will return False otherwise.

• Calling os.path.isdir(path) will return True if the path argument exists and is a folder and will return False otherwise.

Here are some of the implementations:

>>> os.path.exists('C:\\Users')
True
>>> os.path.exists('C:\\mycode')
False
>>> os.path.isdir('
C:\\Users\\Python')
True
>>> os.path.isfile('
C:\\Users\\Python')
False
>>> os.path.isdir('
C:\\Users\\Python\\calc.exe')
False
>>> os.path.isfile('
C:\\Users\\Python\\calc.exe')
True


We can determine whether there is a DVD or flash drive currently attached to the computer by checking for it with the os.path.exists() function. For instance, if I wanted to check for a flash drive with the volume named D:\ on my Windows computer, I could do that with the following:

>>> os.path.exists('D:\\')
False


These were some of the commonly used functions from the os.path module but if your interested to explore os.path module in details, the full documentation for the os.path module is on the Python website at https://docs.python.org/3/library/os.path.html

Till we meet next, keep practicing and learning Python as Python is easy to learn!

 
Share:

Tuesday, November 27, 2018

More on File Handling in Python

Opening and Reading Text Files by Buffer Size

The read() function in Python allows us to specify the buffer size we want so that our program does not use too much memory resources. The read() takes a parameter which specifies the data to be fetched from a file in bytes. Lets see this through a program:

sourcefile = open('cities.txt','r')
targetfile = open('mycities.txt','w')

mytext = sourcefile.read(10)

while len(mytext):
   
    targetfile.write(mytext)
    mytext = sourcefile.read(10)



We started by opening our cities.txt file in read mode with  sourcefile as file handler/file object. Next we created a new file mycities.txt and opened it in write mode with targetfile as file handler. In the line mytext = sourcefile.read(10), the read function as an argument , 10, which tells the read() to only read 10 bytes. The content from cities.txt is saved in the variable mytext.

In the while statement we have use this mytext variable to check when its length is zero. As long as the length is not zero, the loop will run and content from mytext will be written to mycities.txt file. After writing the message again the next 10 bytes data/content is read from cities.txt and saved in the variable mytext. This goes on until the entire content from cities.txt is saved in the mycities.txt file.

If mycities.txt didn't exist then it'll be created when we use open('mycities.txt','w'). The output of mycities.txt file should be the same as that of cities.txt file as shown below:

Hyderabad
Mumbai
Delhi
Chennai
Kolkata
Bengaluru
Jabalpur

How to verify that only 10 bytes of content was read at a time? try the program below and see the output:

sourcefile = open('cities.txt','r')
targetfile = open('mycities.txt','w')

mytext = sourcefile.read(10)

while len(mytext):
   
    targetfile.write(mytext + '\n')
    mytext = sourcefile.read(10)

   

The output of mycities.txt file should now be:
    
Hyderabad

Mumbai
Del
hi
Chennai

Kolkata
B
engaluru
J
abalpur


Handling binary files

The read and write operations of Binary files are also handled like text files, the only difference is in the syntax used in opening the file. We use 'rb', 'wb' instead of 'r' and 'w' for the opening modes. The program shown below explains the read and write operations.

sourcefile = open('m2.jpg','rb')
targetfile = open('mym2.jpg','wb')

myimage = sourcefile.read()
targetfile.write(myimage)



When we run the program an additional image file named mym2.jpg is created in our examples folder where m2.jpg is present. It looks exactly like m2.jpg

Deleting and Renaming Files

In Python the two functions used deleting and renaming files are the remove() and rename() functions. These functions are available in the os module and have to be imported before we can use them.

1. remove() function

The syntax to remove file is remove("filename"). To remove/delete mycities.txt file we will use the following code:

import os

os.remove("mycities.txt")



When we run the program the file mycities.txt should be deleted from the stored location.

2. rename() function    
   
The syntax to rename file is rename("oldfilename","newfilename"). To rename cities.txt file to newcities.txt  we will use the following code:

import os

os.rename("cities.txt","newcities.txt")


When we run the program the file cities.txt should be renamed to newcities.txt in the stored location.


Creating New Folders

Through programs we can create new folders (directories) with the os.makedirs() function. In order to create a new folder 'MyCode' in F:\Python_Code\examples we'll use the following code:

import os

os.makedirs('F:\Python_Code\examples\MyCode')


This creates a new folder MyCode inside the examples directory

If we used 'C:\Python_Code\examples\MyCode' with makedirs(), a new directory structure will be created from scratch in the C: drive .

After running the code just check if the desired folder and directory structure was created at the expected locations.

There is a separate os.path module which contains many helpful functions related to filenames
and file paths. In the next post we shall focus on this module. Till we meet next keep practicing and learning Python as Python is....






Share:

Monday, November 26, 2018

File Handling in Python

We usually use variables to store data while our program is running, but if we need our data to persist even after the program has finished, we need to save it to a file. Se we can think of a file’s contents as a single string value, potentially gigabytes in size. Thus an incredible amount of data is available in text files. Text files can contain weather data, traffic data, socioeconomic data, literary works, and more.
A file has two key properties: a filename (usually written as one word) and a path. The path specifies the location of a file on the computer. For example, there is a file on my computer with the filename euler.txt in the path F:\Python_Code\examples. The part of the filename after the last period is called the file’s extension and tells you a file’s type. euler.txt is a text document.

Reading from a file

Reading from a file is useful in data analysis applications and also applicable to any situation in which we want to analyze or modify information stored in a file. When working with the content in a text file the first step is to read the file into memory. We can either read the entire contents of a file, or
work through the file one line at a time.

1. Reading an entire file
Let’s start with a file that contains Euler's number e with numerical value of e truncated to 50 decimal places with 10 decimal places per line:

2.7182818284
   5904523536
   0287471352
   6624977572
   4709369995


I've saved this file as euler.txt in F:\Python_Code\examples, where I store all my programs. Here’s a program euler_reader.py, that opens this file, reads it, and prints the contents of the file to the screen: 
with open('euler.txt') as file_object:
   
    file_content = file_object.read()
   
    print(file_content)


The output of the program is shown below:

01

To do any work with a file, even just printing its contents, you first need to open the file to access it. This is accomplished by the open(). The open() function needs one argument: the name of the file you want to open. Python looks for this file in the directory where the program that’s currently being executed is stored.

In this example, euler_reader.py is currently running, so Python looks for euler.txt in the directory where euler_reader.py is stored. The open() function returns an object representing the file. Here, open('euler.txt') returns an object representing euler.txt. Python stores this object in file_object.
The keyword with closes the file once access to it is no longer needed. Notice how we call open() in this program but not close(). We can open and close the file by calling open() and close(), but sometimes a bug in our program may prevent the close() statement from being executed, thus the file may never close. The improperly closed files can cause data to be lost or corrupted. Also if we call close() too early in our program, we might trying to work with a closed file (a file you can’t access), which leads to more errors. It’s not always easy to know exactly when you should close a file, but with the structure shown here, Python will figure that out for you. Thus, just open the file and work with it as desired, trusting that Python will close it automatically when the time is right.

Once we have a file object representing pi_digits.txt, we use the read() method in the second line of our program to read the entire contents of the file and store it as one long string in file_content. When we print the value of file_content, we get the entire text file back. The only difference between this output and the original file is the extra blank line at the end of the output. The blank line appears because read() returns an empty string when it reaches the end of the file; this empty string shows up as a blank line. If you want to remove the extra blank line, you can use rstrip() in the print statement:
The revised code and it's output is shown below :

with open('euler.txt') as file_object:
   
    file_content = file_object.read()
   
    print(file_content.rstrip())
 

02

By default when using the open() function, when we pass a file to the open  () Python looks in the directory where the file that’s currently being executed (that is, your .py program file) is stored. In case the file is stored in a different directory, we need to provide a file path, which tells Python to look in a specific location on your system.

Let us create a file Names.txt in F:/Python_Code/examples/Data. Because Names.txt is inside Python_Code, we could use a relative file path to open a file from Data. A relative file path tells Python to look for a given location relative to the directory where the currently running program file
is stored. See the code below:

with open('Data/Names.txt') as file_object:
   
    file_content = file_object.read()
   
    print(file_content.rstrip())

The line with open('Data/Names.txt') as file_object: tells Python to look for the desired .txt file in the folder Data and assumes that Data is located inside examples folder which is inside Python_Code folder.

We can also tell Python exactly where the file is on your computer regardless of where the program that’s being executed is stored. This is called an absolute file path. You use an absolute path if a relative path doesn’t work. For instance I have a folder Text_files in  F:/Text_files. In the folder I have a file positions.txt. In order to access positions.txt I have to provide the absolute file path, which in this case is F:/Text_files/positions.txt.

To print the content of positions.txt the code is shown below:

with open('F:/Text_files/positions.txt') as file_object:
   
    file_content = file_object.read()
   
    print(file_content.rstrip())


The output of the program is shown below:

03

In case if Absolute paths are longer than relative paths,  it’s helpful to store them in a variable and then pass that variable to open().

For example my_path = 'F:/Text_files/positions.txt' and then use this in the open() as follows:

with open('my_path') as file_object:

The revised program is as shown below:

my_path = 'F:/Text_files/positions.txt'

with open(my_path) as file_object:
   
    file_content = file_object.read()
   
    print(file_content.rstrip())


2. Reading line by line from a file 

We can use a for loop on the file object to examine each line from a file one at a time. Thus to read each line from our file euler .txt we can use the following program:

my_path = 'euler.txt'

with open(my_path) as file_object:
   
    for line in file_object:
       
        print(line) 

   
After we call open(), an object representing the file and its contents is stored in the variable file_object. To examine the file’s contents, we work through each line in the file by looping over the file object. The output is shown below:

04

Note the blank lines appear because an invisible newline character is at the end of each line in the text file. The print statement adds its own newline each time we call it, so we end up with two newline characters at the end of each line: one from the file and one from the print statement. Using rstrip() on each line in the print statement eliminates these extra blank lines. The revised program and it's output is shown below:

my_path = 'euler.txt'

with open(my_path) as file_object:
   
    for line in file_object:
       
        print(line.rstrip())


05

A point to be noted is that when we use with, the file object returned by open() is only available inside the with block that contains it. So if we want to retain access to a file’s contents outside the with block, we can store the file’s lines in a list inside the block and then work with that list.  In this way we can process parts of the file immediately and postpone some processing for later in the program.

The revised program and it's output using above mentioned approach is shown below:
my_path = 'euler.txt'

with open(my_path) as file_object:
   
    lines = file_object.readlines()
   
for line in lines:
       
    print(line.rstrip())

06

In case you want to print the value of euler's number in one line, here is the code:
my_path = 'euler.txt'

with open(my_path) as file_object:
   
    lines = file_object.readlines()
   
myline = ''

for line in lines:
   
    myline+=line.rstrip()
       
print(myline)

The output is shown below:

07
The output contains the whitespace that was on the left side of the digits in each line, but we can get rid of that by using strip() instead of rstrip():

my_path = 'euler.txt'

with open(my_path) as file_object:
   
    lines = file_object.readlines()
   
myline = ''

for line in lines:
   
    myline+=line.strip()
       
print(myline)
   
The output without whitespaces is shown below:

08

We can also check the presence of data in a file. For example in the file Names.txt if I want to check whether Tom is present I can do in the following way:
my_path = 'Data/Names.txt'

with open(my_path) as file_object:
   
    lines = file_object.readlines()
   
myline = ''

for line in lines:
   
    myline += line
       
myname = input("Enter your name to check it's existence in the file\n")

if myname in myline:
   
    print("\nThe name :" + myname + " is present in the file")
   
else:
   
    print("\nThe name :" + myname + " is not present in the file")   
   
The output of the program is shown below:

09

Writing to a file 

After learning how to read from a file, it's time to learn how to write to a file in order to save data. When we write text to a file, the output will still be available after we close the terminal containing our program’s output. We can examine output after a program finishes running, and can share the output files with others as well. It is also possible to write programs that read the text back into memory and work with it again later.

1. Writing to an empty file

In order to write text to a file, we use open() with a second argument telling Python that you want to write to the file. To see how this works, let’s write a simple program to store city name in a file instead of printing it to the screen:

filename = 'cities.txt'

with open(filename,'w') as file_object:
   
    file_object.write("Hyderabad")

The call to open() in this example has two arguments, the name of the file we want to open and the mode in which we want to open the file. Thus open(filename,'w') tells Python to open cities.txt file in a write mode. It is possible to open a file in read mode ('r'), write mode ('w'), append mode ('a'), or a mode that allows you to read and write to the file ('r+'). If you omit the mode argument, Python opens the file in read-only mode by default.

The open() function automatically creates the file you’re writing to if it doesn’t already exist. However, be careful opening a file in write mode ('w') because if the file does exist, Python will erase the file before returning the file object.

Finally we use the write() method on the file object to write a string to the file. This program has no terminal output, but if you open the file you'll see the string "Hyderabad" written in it.
The write() function doesn’t add any newlines to the text we write. So if we write more than one line without including newline characters, our file may not look the way wewant it to. For example I add more cities to our cities.txt file as shown below:

filename = 'cities.txt'

with open(filename,'w') as file_object:
   
    file_object.write("Hyderabad")
    file_object.write("Mumbai")
    file_object.write("Delhi")
    file_object.write("Chennai")
    file_object.write("Kolkata")
    file_object.write("Bengaluru")
   
The content in the file will be "HyderabadMumbaiDelhiChennaiKolkataBengaluru" which was not expected. Thus adding newlines in the write() may do the trick. See the revised code below:
filename = 'cities.txt'

with open(filename,'w') as file_object:
   
    file_object.write("Hyderabad\n")
    file_object.write("Mumbai\n")
    file_object.write("Delhi\n")
    file_object.write("Chennai\n")
    file_object.write("Kolkata\n")
    file_object.write("Bengaluru\n")

Now if we open cities.txt file the content will be as shown below:
Hyderabad
Mumbai
Delhi
Chennai
Kolkata
Bengaluru


2. Appending to an empty file 

In case you want to add more cities to the file cities.txt without erasing the existing content, open the file using append mode. See the code below:
filename = 'cities.txt'

with open(filename,'a') as file_object:
   
    file_object.write("Jabalpur\n")

Now if we open cities.txt file the content will be as shown below:
Hyderabad
Mumbai
Delhi
Chennai
Kolkata
Bengaluru
Jabalpur


Thus our file is with the original contents of the file, followed by the new content we just added. This brings to an end of today's discussion on file handling. As an exercise create a file say pizzas containing your favorite pizzas using open() and write(). Then read the content of the file and print the result on the screen. Till we meet next keep practicing and learning Python as Python is....



   
   











Share:

Wednesday, November 21, 2018

Private variable and method in Python

Python doesn't have real private variables and methods. Thus there is an adopted convention of having two underlines at the beginning make a variable and a method private. The following example explains this behavior:

class Amount():
   
    __value = 50
   
    def __display(self):
       
        print ("In class A")
  
 def myvalue(self):
       
        print("Value is "+ str(Amount.__value))   
       

obj1 = Amount()
obj1.myvalue()
obj1.__display()
print(obj1.__value)

In the preceding program, __display() is the private method and __value is the private variable. Let's see the output:



In the myvalue() method, the __value variable can be accessed as shown in the output (Value is printed). Thus outside the class, we cannot access the private method as well as the private variable, but inside the class, we can access the private variables.

Now, let's rewrite the program and try to access private variables and the private method from outside the class.

class Amount():
   
    __value = 50
   
    def __display(self):
       
        print ("In class A")
    def myvalue(self):
       
        print("Value is "+ str(Amount.__value))   
       

obj1 = Amount()
obj1.myvalue()
obj1._Amount__display()
print(obj1._Amount__value)


The output of the program is shown below:



Thus we can access private variables and the private method from outside the class using the syntax like instance _class-name__private-attribute.(Example obj1._Amount__value , obj1._Amount__display())

The benefit of accessing private variable outside the class is to prevent the class method and variable being changed by others accidentally. See the example below:

 class Amount():
  
    __value = 50
  
    def __display(self):
      
        print ("In class Amount")
      
    def display(self):
      
        self.__display()  
      
      
class new(Amount):
  
    def __display(self):
      
        print ("In class new")
  

obj1 = Amount()
obj1.display()


obj2 = new()
obj2.display()





As you can see, obj2.display() didn't call obj2.__display() as we could expect. Actually this is the correct behavior for __. So when you create a method starting with __ you're saying that you don't want anybody to override it, it will be accessible just from inside the own class.

In Python, there is a concept called name mangling, which means that there is a limited support for a valid use-case for class-private members basically to avoid name clashes of names with names defined by subclasses. Any identifier of the form __display(at least two leading underscores or at most one trailing underscore) is replaced with _classname__display, where classname is the current class name with leading underscore(s) stripped. As long as it occurs within the definition of the class, this mangling is done. This is helpful for letting subclasses override methods without breaking intraclass method calls.


Private variables and methods are used for special purpose hence during coding use of _ and __ should be avoided unless you wanna specify private behavior. Here we end our discussion. In the next post we'll discuss about file handling in Python.Till then keep learning Python as Python is easy to learn!  
Share: