Python Notes - 4
Python Notes - 4
As our application program grows larger in size with a lot of modules, we place similar modules in one
package and different modules in different packages.
This makes a project (program) easy to manage and conceptually clear.
Directory(folder) can contain subdirectories and files, a Python package can have sub-packages and modules.
A directory must contain a file named __init__.py in order for Python to consider it as a package. This file can
be left empty but we generally place the initialization code for that package in this file.
Example
we are developing a game. One possible organization of packages and modules could be as shown in the figure
below.
Paste (module)
Colgate (function)
My name is Colgate cost is Rs:100
Pepsodent (function)
My name is Pepsodent cost is Rs:150
Closeup (function)
My name is Closeup cost is Rs:200
Step 1: we need to create a Folder(directory) in the python path C:\Program Files\Python39\Lib
( we are creating folder Provision_Shop in above path)
Step 2: with that folder we need to create required modules…
(we are ceating module1 Soap.py with functions of Santoor, Lux, Chintol)
(we are ceating module2 Paste.py with functions of Colgate, Pepsodent, Closeup)
Step 3: Create a __init__.py file with the Provision_Shop folder
from Provision_Shop.Soap import *
from Provision_Shop.Paste import *
Santoor()
Lux()
Chintol()
Colgate()
Python Dictionary
Python dictionary is an unordered collection of items. Each item of a dictionary has a key/value pair.
Dictionaries are optimized to retrieve values when the key is known.
Creating Python Dictionary
Creating a dictionary is as simple as placing items inside curly braces {} separated by commas.
An item has a key and a corresponding value that is expressed as a pair (key: value).
While the values can be of any data type and can repeat, keys must be of immutable type (string, number or tuple with
immutable elements) and must be unique.
# empty dictionary
my_dict = {}
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
Accessing Elements from Dictionary
get() method.
# get vs [] for retrieving elements
my_dict = {'name': 'Jack', 'age': 26} print(my_dict.get('address')) error as none
print(my_dict['name']) print(my_dict['address']) error
print(my_dict.get('age'))
Changing and Adding Dictionary elements
# Changing and adding Dictionary Elements #Output: {'age': 27, 'name': 'Jack'}
my_dict = {'name': 'Jack', 'age': 26} print(my_dict)
print(my_dict)
# add item
# update value my_dict['address'] = 'Downtown'
my_dict['age'] = 27
# Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}
print(my_dict)
Removing elements from Dictionary
We can remove a particular item in a dictionary by using the pop() method. This method removes an item with the
provided key and returns the value
# Removing elements from a dictionary # Output: {1: 1, 2: 4, 3: 9}
print(squares)
# create a dictionary
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} # remove all items
squares.clear()
# remove a particular item, returns its value
# Output: 16 # Output: {}
print(squares.pop(4)) print(squares)
We can specify the mode while opening a file. In mode, we specify whether we want to read r, write w or append a to the file.
The default is reading in text mode. In this mode, we get strings when reading from the file.
f = open("test.txt",’r’) # equivalent to 'r' or 'rt'
f = open("test.txt",'w') # write in text mode
f = open("img.bmp",'r+b') # read and write in binary mode
Moreover, the default encoding is platform dependent. In windows, it is cp1252 but utf-8 in Linux.
f = open("test.txt", mode='r', encoding='utf-8')
We can change our current file cursor (position) using the seek() method. Similarly, the tell() method returns our current position
(in number of bytes).
>>> f.tell() # get the current file position
56
We can read a file line-by-line using a for loop. This is both efficient and fast.
>>> for line in f:
... print(line, end = '')
...
This is my first file
This file
contains three lines
we can use the f.tell() method to read individual lines of a file. This method reads a file till the newline, including the newline
character.
>>> f.readline()
'This is my first file\n'
>>> f.readline()
'This file\n'
>>> f.readline()
'contains three lines\n'
>>> f.readline()
''
the readlines() method returns a list of remaining lines of the entire file. All these reading methods return empty values when the
end of file (EOF) is reached.
>>> f.readlines()
['This is my first file\n', 'This file\n', 'contains three lines\n']
Method Description
close() Closes an opened file. It has no effect if the file is already closed.
detach() Separates the underlying binary buffer from the TextIOBase and returns it.
read(n) Reads at most n characters from the file. Reads till end of file if it is negative or None.
readline(n=-1) Reads and returns one line from the file. Reads in at most n bytes if specified.
readlines(n=-1) Reads and returns a list of lines from the file. Reads in at most n bytes/characters if specified.
seek(offset,from=SEEK_SET) Changes the file position to offset bytes, in reference to from (start, current, end).
truncate(size=None) Resizes the file stream to size bytes. If size is not specified, resizes to current location.
stu1=Student()
stu1.name="AAA"
stu1.marks=30
print(stu1.name)
print(stu1.marks)
stu2=Student()
stu2.name="BBB"
stu2.marks=50
print(stu2.name)
print(stu2.marks)
stu1=Student("AAA",50)
res=stu1.chkres()
print(res)
Inheritance
Inheritance is a way of creating a new class for using details of an existing class without modifying it. The newly
formed class is a derived class (or child class). Similarly, the existing class is a base class (or parent class).
class Voting:
def chkvoting(self):
if self.age>18:
return "Eligible for Voting"
else:
return "Not Eligible for Voting"
class Student(Voting):
def chkres(self):
if self.marks>40:
return "Pass"
else:
return "Fail"
def __init__(self,name,age,marks):
self.name=name
self.age=age
self.marks=marks
stu1=Student("AAA",15,50)
res=stu1.chkres()
print(res)
vot=stu1.chkvoting()
print(vot)
Encapsulation
Using OOP in Python, we can restrict access to methods and variables. This prevents data from direct
modification which is called encapsulation.
class Computer:
x=5000
def __init__(self):
self.maxprice = 900
c = Computer()
print("X value for C:",c.x)
print("Selling Price",c.maxprice)
Polymorphism
Polymorphism is an ability (in OOP) to use a common interface for multiple forms (data types).
class Parrot:
def fly(self):
print("Parrot can fly")
def swim(self):
print("Parrot can't swim")
class Penguin:
def fly(self):
print("Penguin can't fly")
def swim(self):
print("Penguin can swim")
# common interface
def flying_test(bird):
bird.fly()
#instantiate objects
blu = Parrot()
peggy = Penguin()