SlideShare a Scribd company logo
UNIT 3 OBJECTS ,
CLASSES & FILES
Python OOPs Concepts
Like other general-purpose programming languages, Python is
also an object-oriented language since its beginning. It allows us
to develop applications using an Object-Oriented approach.
In Python, we can easily create and use classes and objects.
An object-oriented paradigm is to design the program using
classes and objects. The object is related to real-word entities such
as book, house, pencil, etc. The oops concept focuses on writing
the reusable code. It is a widespread technique to solve the
problem by creating objects.
Major principles of object-oriented
programming system are given below.
1. Class
2. Object
3. Method
4. Inheritance
5. Polymorphism
6. Data Abstraction
7. Encapsulation
Class
The class can be defined as a collection of objects. It is a logical entity that has some
specific attributes and methods. For example: if you have an employee class, then it should
contain an attribute and method, i.e. an email id, name, age, salary, etc.
Syntax
class ClassName:
<statement-1>
.
.
<statement-N>
A class is a blueprint for the object
Example:
class car:
def __init__(self,modelname, year):
self.modelname = modelname
self.year = year
def display(self):
print(self.modelname,self.year)
Object
The object is an entity that has state and behavior. It may be any real-world object like the
mouse, keyboard, chair, table, pen, etc.
Everything in Python is an object, and almost everything has attributes and methods. All
functions have a built-in attribute __doc__, which returns the docstring defined in the
function source code.
When we define a class, it needs to create an object to allocate the memory.
Example:
Example:
class car:
def __init__(self,modelname, year):
self.modelname = modelname
self.year = year
def display(self):
print(self.modelname,self.year)
c1 = car("Toyota", 2016)
c1.display()
The __init__() Function
All classes have a function called __init__(), which is always
executed when the class is being initiated.
Use the __init__() function to assign values to object properties,
or other operations that are necessary to do when the object is
being created:
The first argument of every method is a reference to the current
instance of the class
By convention, we name this argument self
In __init__, self refers to the object currently being created; so,
in other class methods, it
refers to the instance whose method was called Similar to the
keyword this in Java or C++.
Example
Create a class named Person, use the __init__() function to
assign values for name and age:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
Object Methods
Example
Insert a function that prints a greeting, and execute it on the
p1 object:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
The self Parameter
The self parameter is a reference to the current instance of
the class, and is used to access variables that belongs to the
class.
It does not have to be named self , you can call it whatever
you like, but it has to be the first parameter of any function in
the class:
Example
Use the words mysillyobject and abc instead of self:
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()
Inheritance
Inheritance is the most important aspect of object-oriented
programming, which simulates the real-world concept of
inheritance.
It specifies that the child object acquires all the properties and
behaviors of the parent object.
By using inheritance, we can create a class which uses all the
properties and behavior of another class.
The new class is known as a derived class or child class, and
the one whose properties are acquired is known as a base class
or parent class.
It provides the re-usability of the code.
# parent class
class Bird:
def __init__(self):
print("Bird is ready")
def whoisThis(self):
print("Bird")
def swim(self):
print("Swim faster")
# child class
class Penguin(Bird):
def __init__(self):
# call super() function
super().__init__()
print("Penguin is ready")
def whoisThis(self):
print("Penguin")
def run(self):
print("Run faster")
peggy = Penguin()
peggy.whoisThis()
peggy.swim()
peggy.run()
Encapsulation
Using OOP in Python, we can restrict access to methods and variables. This prevents data
from direct modification which is called encapsulation. In Python, we denote private attributes
using underscore as the prefix i.e single _ or double __.
class Computer:
def __init__(self):
self.__maxprice = 900
def sell(self):
print("Selling Price: {}".format(self.__maxprice))
def setMaxPrice(self, price):
self.__maxprice = price
c = Computer()
c.sell()
# change the price
c.__maxprice = 1000
c.sell()
# using setter function
c.setMaxPrice(1000)
c.sell()
Polymorphism
Polymorphism is an ability (in OOP) to use a common interface for multiple forms (data types).
Suppose, we need to color a shape, there are multiple shape options (rectangle, square, circle).
However we could use the same method to color any shape. This concept is called
Polymorphism.
class Parrot:
def fly(self):
print("Parrot can fly")
def swim(self): p
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()
# passing the object
flying_test(blu)
flying_test(peggy)
File Objects in Python
Files
Files are named locations on disk to store related information.
They are used to permanently store data in a non-volatile memory (e.g. hard
disk).
Since Random Access Memory (RAM) is volatile (which loses its data when the
computer is turned off), we use files for future use of the data by permanently
storing them.
When we want to read from or write to a file, we need to open it first. When we
are done, it needs to be closed so that the resources that are tied with the file are
freed.
Hence, in Python, a file operation takes place in the following order:
1. Open a file
2. Read or write (perform operation)
3. Close the file
1 . Python File Open -
The key function for working with files in Python is the open() function.
The open() function takes two parameters; filename, and mode.
There are four different methods (modes) for opening a file:
1. "r" - Read - Default value. Opens a file for reading, error if the file does
not exist
2. "a" - Append - Opens a file for appending, creates the file if it does not
exist
3. "w" - Write - Opens a file for writing, creates the file if it does not exist
4. "x" - Create - Creates the specified file, returns an error if the file exists
Syntax - f = open("demofile.txt")
f = open("demofile.txt", "rt")
Mode Description
r Opens a file for reading. (default)
w
Opens a file for writing. Creates a new file if it
does not exist or truncates the file if it exists.
x
Opens a file for exclusive creation. If the file
already exists, the operation fails.
a
Opens a file for appending at the end of the file
without truncating it. Creates a new file if it does
not exist.
t Opens in text mode. (default)
b Opens in binary mode.
+ Opens a file for updating (reading and writing)
2 . Python File Read -
1. The open() function returns a file object, which has
a read() method for reading the content of the file:
Example
f = open("demofile.txt", "r")
print(f.read())
2. If the file is located in a different location, you will have to
specify the file path, like this:
Example
f = open("D:myfileswelcome.txt", "r")
print(f.read())
3. By default the read() method returns the whole text, but
you can also specify how many characters you want to
return:
Example
f = open("demofile.txt", "r")
print(f.read(5))
3 . Python Write/Create File -
1. Write to an Existing File
To write to an existing file, you must add a parameter to
the open() function:
"a" - Append - will append to the end of the file
"w" - Write - will overwrite any existing content
2. Create a File
To create a new file in Python, use the open() method, with one of the
following parameters:
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist
Method Description
close() Closes the file
detach() Returns the separated raw stream from the buffer
fileno() Returns a number that represents the stream, from the operating system's
perspective
flush() Flushes the internal buffer
isatty() Returns whether the file stream is interactive or not
read() Returns the file content
readable() Returns whether the file stream can be read or not
readline() Returns one line from the file
readlines() Returns a list of lines from the file
seek() Change the file position
seekable() Returns whether the file allows us to change the file position
tell() Returns the current file position
truncate() Resizes the file to a specified size
writable() Returns whether the file can be written to or not
write() Writes the specified string to the file
writelines() Writes a list of strings to the file
Built –in methods in python
Command Line Arguments in Python
The arguments that are given after the name of the program in the
command line shell of the operating system are known
as Command Line Arguments.
Python provides various ways of dealing with these types of
arguments.
The three most common are:
1. Using sys.argv
2. Using getopt module
3. Using argparse module
Using sys.argv
The sys module provides functions and variables used to
manipulate different parts of the Python runtime environment.
This module provides access to some variables used or maintained
by the interpreter and to functions that interact strongly with the
interpreter.
One such variable is sys.argv which is a simple list structure. It’s
main purpose are:
1. It is a list of command line arguments.
2. len(sys.argv) provides the number of command line arguments.
3. sys.argv[0] is the name of the current Python script.
# Python program to demonstrate
# command line arguments
import sys
# total arguments
n = len(sys.argv)
print("Total arguments passed:", n)
# Arguments passed
print("nName of Python script:", sys.argv[0])
print("nArguments passed:", end = " ")
for i in range(1, n):
print(sys.argv[i], end = " ")
# Addition of numbers
Sum = 0
# Using argparse module
for i in range(1, n):
Sum += int(sys.argv[i])
print("nnResult:", Sum)
Using getopt module
Python getopt module is similar to the getopt() function of C.
Unlike sys module getopt module extends the separation of the input string by parameter
validation.
It allows both short, and long options including a value assignment. However, this
module requires the use of the sys module to process input data properly.
To use getopt module, it is required to remove the first element from the list of
command-line arguments.
Syntax: getopt.getopt(args, options, [long_options])
Parameters:
args: List of arguments to be passed.
options: String of option letters that the script want to recognize. Options that
require an argument should be followed by a colon (:).
long_options: List of string with the name of long options. Options that
require arguments should be followed by an equal sign (=).
Return Type: Returns value consisting of two elements: the first is a list of
(option, value) pairs. The second is the list of program arguments left after
the option list was stripped.
Using argparse module
Using argparse module is a better option than the
above two options as it provides a lot of options
such as positional arguments, default value for
arguments, help message, specifying data type of
argument etc.
Note: As a default optional argument, it includes
-h, along with its long version –help.

More Related Content

Similar to Master of computer application python programming unit 3.pdf (20)

Python-FileHandling.pptx
Python-FileHandling.pptxPython-FileHandling.pptx
Python-FileHandling.pptx
Karudaiyar Ganapathy
 
Python-files
Python-filesPython-files
Python-files
Krishna Nanda
 
chapter 2(IO and stream)/chapter 2, IO and stream
chapter 2(IO and stream)/chapter 2, IO and streamchapter 2(IO and stream)/chapter 2, IO and stream
chapter 2(IO and stream)/chapter 2, IO and stream
amarehope21
 
FIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxFIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptx
Ashwini Raut
 
Python File Handling52616416416 ppt.pptx
Python File Handling52616416416 ppt.pptxPython File Handling52616416416 ppt.pptx
Python File Handling52616416416 ppt.pptx
saiwww3841k
 
7 Data File Handling
7 Data File Handling7 Data File Handling
7 Data File Handling
Praveen M Jigajinni
 
These questions will be a bit advanced level 2
These questions will be a bit advanced level 2These questions will be a bit advanced level 2
These questions will be a bit advanced level 2
sadhana312471
 
Module, mixins and file handling in ruby
Module, mixins and file handling in rubyModule, mixins and file handling in ruby
Module, mixins and file handling in ruby
Ananta Lamichhane
 
Chapter - 5.pptx
Chapter - 5.pptxChapter - 5.pptx
Chapter - 5.pptx
MikialeTesfamariam
 
02 fundamentals
02 fundamentals02 fundamentals
02 fundamentals
sirmanohar
 
Linux basics
Linux basicsLinux basics
Linux basics
sirmanohar
 
Python Lecture 9
Python Lecture 9Python Lecture 9
Python Lecture 9
Inzamam Baig
 
Python programming computer science and engineering
Python programming computer science and engineeringPython programming computer science and engineering
Python programming computer science and engineering
IRAH34
 
File handling for reference class 12.pptx
File handling for reference class 12.pptxFile handling for reference class 12.pptx
File handling for reference class 12.pptx
PreeTVithule1
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
vsol7206
 
working with files
working with filesworking with files
working with files
SangeethaSasi1
 
DFH PDF-converted.pptx
DFH PDF-converted.pptxDFH PDF-converted.pptx
DFH PDF-converted.pptx
AmitKaur17
 
Chapter 08 data file handling
Chapter 08 data file handlingChapter 08 data file handling
Chapter 08 data file handling
Praveen M Jigajinni
 
software construction and development week 3 Python lists, tuples, dictionari...
software construction and development week 3 Python lists, tuples, dictionari...software construction and development week 3 Python lists, tuples, dictionari...
software construction and development week 3 Python lists, tuples, dictionari...
MuhammadBilalAjmal2
 
Data File Handling in Python Programming
Data File Handling in Python ProgrammingData File Handling in Python Programming
Data File Handling in Python Programming
gurjeetjuneja
 
chapter 2(IO and stream)/chapter 2, IO and stream
chapter 2(IO and stream)/chapter 2, IO and streamchapter 2(IO and stream)/chapter 2, IO and stream
chapter 2(IO and stream)/chapter 2, IO and stream
amarehope21
 
FIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptxFIle Handling and dictionaries.pptx
FIle Handling and dictionaries.pptx
Ashwini Raut
 
Python File Handling52616416416 ppt.pptx
Python File Handling52616416416 ppt.pptxPython File Handling52616416416 ppt.pptx
Python File Handling52616416416 ppt.pptx
saiwww3841k
 
These questions will be a bit advanced level 2
These questions will be a bit advanced level 2These questions will be a bit advanced level 2
These questions will be a bit advanced level 2
sadhana312471
 
Module, mixins and file handling in ruby
Module, mixins and file handling in rubyModule, mixins and file handling in ruby
Module, mixins and file handling in ruby
Ananta Lamichhane
 
02 fundamentals
02 fundamentals02 fundamentals
02 fundamentals
sirmanohar
 
Python programming computer science and engineering
Python programming computer science and engineeringPython programming computer science and engineering
Python programming computer science and engineering
IRAH34
 
File handling for reference class 12.pptx
File handling for reference class 12.pptxFile handling for reference class 12.pptx
File handling for reference class 12.pptx
PreeTVithule1
 
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reugeFile handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
vsol7206
 
DFH PDF-converted.pptx
DFH PDF-converted.pptxDFH PDF-converted.pptx
DFH PDF-converted.pptx
AmitKaur17
 
software construction and development week 3 Python lists, tuples, dictionari...
software construction and development week 3 Python lists, tuples, dictionari...software construction and development week 3 Python lists, tuples, dictionari...
software construction and development week 3 Python lists, tuples, dictionari...
MuhammadBilalAjmal2
 
Data File Handling in Python Programming
Data File Handling in Python ProgrammingData File Handling in Python Programming
Data File Handling in Python Programming
gurjeetjuneja
 

Recently uploaded (20)

LDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad UpdatesLDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad Updates
LDM & Mia eStudios
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
How to Create Time Off Request in Odoo 18 Time Off
How to Create Time Off Request in Odoo 18 Time OffHow to Create Time Off Request in Odoo 18 Time Off
How to Create Time Off Request in Odoo 18 Time Off
Celine George
 
Coleoptera: The Largest Insect Order.pptx
Coleoptera: The Largest Insect Order.pptxColeoptera: The Largest Insect Order.pptx
Coleoptera: The Largest Insect Order.pptx
Arshad Shaikh
 
How to Create a Stage or a Pipeline in Odoo 18 CRM
How to Create a Stage or a Pipeline in Odoo 18 CRMHow to Create a Stage or a Pipeline in Odoo 18 CRM
How to Create a Stage or a Pipeline in Odoo 18 CRM
Celine George
 
Cloud Computing ..PPT ( Faizan ALTAF )..
Cloud Computing ..PPT ( Faizan ALTAF )..Cloud Computing ..PPT ( Faizan ALTAF )..
Cloud Computing ..PPT ( Faizan ALTAF )..
faizanaltaf231
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
parmarjuli1412
 
la storia dell'Inghilterra, letteratura inglese
la storia dell'Inghilterra, letteratura inglesela storia dell'Inghilterra, letteratura inglese
la storia dell'Inghilterra, letteratura inglese
LetiziaLucente
 
Rose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdfRose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdf
kushallamichhame
 
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition IILDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDM & Mia eStudios
 
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdfForestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
ChalaKelbessa
 
Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...
Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...
Pfeiffer "Secrets to Changing Behavior in Scholarly Communication: A 2025 NIS...
National Information Standards Organization (NISO)
 
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptxSEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
PoojaSen20
 
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_HyderabadWebcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
 
How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18
Celine George
 
State institute of educational technology
State institute of educational technologyState institute of educational technology
State institute of educational technology
vp5806484
 
LDMMIA Reiki Yoga S8 Free Workshop Grad Level
LDMMIA Reiki Yoga S8 Free Workshop Grad LevelLDMMIA Reiki Yoga S8 Free Workshop Grad Level
LDMMIA Reiki Yoga S8 Free Workshop Grad Level
LDM & Mia eStudios
 
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Celine George
 
Nice Dream.pdf /
Nice Dream.pdf                              /Nice Dream.pdf                              /
Nice Dream.pdf /
ErinUsher3
 
LDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad UpdatesLDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad Updates
LDM & Mia eStudios
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
How to Create Time Off Request in Odoo 18 Time Off
How to Create Time Off Request in Odoo 18 Time OffHow to Create Time Off Request in Odoo 18 Time Off
How to Create Time Off Request in Odoo 18 Time Off
Celine George
 
Coleoptera: The Largest Insect Order.pptx
Coleoptera: The Largest Insect Order.pptxColeoptera: The Largest Insect Order.pptx
Coleoptera: The Largest Insect Order.pptx
Arshad Shaikh
 
How to Create a Stage or a Pipeline in Odoo 18 CRM
How to Create a Stage or a Pipeline in Odoo 18 CRMHow to Create a Stage or a Pipeline in Odoo 18 CRM
How to Create a Stage or a Pipeline in Odoo 18 CRM
Celine George
 
Cloud Computing ..PPT ( Faizan ALTAF )..
Cloud Computing ..PPT ( Faizan ALTAF )..Cloud Computing ..PPT ( Faizan ALTAF )..
Cloud Computing ..PPT ( Faizan ALTAF )..
faizanaltaf231
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
parmarjuli1412
 
la storia dell'Inghilterra, letteratura inglese
la storia dell'Inghilterra, letteratura inglesela storia dell'Inghilterra, letteratura inglese
la storia dell'Inghilterra, letteratura inglese
LetiziaLucente
 
Rose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdfRose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdf
kushallamichhame
 
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition IILDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDM & Mia eStudios
 
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdfForestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
ChalaKelbessa
 
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptxSEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
SEXUALITY , UNWANTED PREGANCY AND SEXUAL ASSAULT .pptx
PoojaSen20
 
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_HyderabadWebcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
 
How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18
Celine George
 
State institute of educational technology
State institute of educational technologyState institute of educational technology
State institute of educational technology
vp5806484
 
LDMMIA Reiki Yoga S8 Free Workshop Grad Level
LDMMIA Reiki Yoga S8 Free Workshop Grad LevelLDMMIA Reiki Yoga S8 Free Workshop Grad Level
LDMMIA Reiki Yoga S8 Free Workshop Grad Level
LDM & Mia eStudios
 
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Celine George
 
Nice Dream.pdf /
Nice Dream.pdf                              /Nice Dream.pdf                              /
Nice Dream.pdf /
ErinUsher3
 
Ad

Master of computer application python programming unit 3.pdf

  • 1. UNIT 3 OBJECTS , CLASSES & FILES
  • 2. Python OOPs Concepts Like other general-purpose programming languages, Python is also an object-oriented language since its beginning. It allows us to develop applications using an Object-Oriented approach. In Python, we can easily create and use classes and objects. An object-oriented paradigm is to design the program using classes and objects. The object is related to real-word entities such as book, house, pencil, etc. The oops concept focuses on writing the reusable code. It is a widespread technique to solve the problem by creating objects.
  • 3. Major principles of object-oriented programming system are given below. 1. Class 2. Object 3. Method 4. Inheritance 5. Polymorphism 6. Data Abstraction 7. Encapsulation
  • 4. Class The class can be defined as a collection of objects. It is a logical entity that has some specific attributes and methods. For example: if you have an employee class, then it should contain an attribute and method, i.e. an email id, name, age, salary, etc. Syntax class ClassName: <statement-1> . . <statement-N> A class is a blueprint for the object Example: class car: def __init__(self,modelname, year): self.modelname = modelname self.year = year def display(self): print(self.modelname,self.year)
  • 5. Object The object is an entity that has state and behavior. It may be any real-world object like the mouse, keyboard, chair, table, pen, etc. Everything in Python is an object, and almost everything has attributes and methods. All functions have a built-in attribute __doc__, which returns the docstring defined in the function source code. When we define a class, it needs to create an object to allocate the memory. Example: Example: class car: def __init__(self,modelname, year): self.modelname = modelname self.year = year def display(self): print(self.modelname,self.year) c1 = car("Toyota", 2016) c1.display()
  • 6. The __init__() Function All classes have a function called __init__(), which is always executed when the class is being initiated. Use the __init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created: The first argument of every method is a reference to the current instance of the class By convention, we name this argument self In __init__, self refers to the object currently being created; so, in other class methods, it refers to the instance whose method was called Similar to the keyword this in Java or C++.
  • 7. Example Create a class named Person, use the __init__() function to assign values for name and age: class Person: def __init__(self, name, age): self.name = name self.age = age p1 = Person("John", 36) print(p1.name) print(p1.age)
  • 8. Object Methods Example Insert a function that prints a greeting, and execute it on the p1 object: class Person: def __init__(self, name, age): self.name = name self.age = age def myfunc(self): print("Hello my name is " + self.name) p1 = Person("John", 36) p1.myfunc()
  • 9. The self Parameter The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class. It does not have to be named self , you can call it whatever you like, but it has to be the first parameter of any function in the class: Example Use the words mysillyobject and abc instead of self: class Person: def __init__(mysillyobject, name, age): mysillyobject.name = name mysillyobject.age = age def myfunc(abc): print("Hello my name is " + abc.name) p1 = Person("John", 36) p1.myfunc()
  • 10. Inheritance Inheritance is the most important aspect of object-oriented programming, which simulates the real-world concept of inheritance. It specifies that the child object acquires all the properties and behaviors of the parent object. By using inheritance, we can create a class which uses all the properties and behavior of another class. The new class is known as a derived class or child class, and the one whose properties are acquired is known as a base class or parent class. It provides the re-usability of the code.
  • 11. # parent class class Bird: def __init__(self): print("Bird is ready") def whoisThis(self): print("Bird") def swim(self): print("Swim faster") # child class class Penguin(Bird): def __init__(self): # call super() function super().__init__() print("Penguin is ready") def whoisThis(self): print("Penguin") def run(self): print("Run faster") peggy = Penguin() peggy.whoisThis() peggy.swim() peggy.run()
  • 12. Encapsulation Using OOP in Python, we can restrict access to methods and variables. This prevents data from direct modification which is called encapsulation. In Python, we denote private attributes using underscore as the prefix i.e single _ or double __. class Computer: def __init__(self): self.__maxprice = 900 def sell(self): print("Selling Price: {}".format(self.__maxprice)) def setMaxPrice(self, price): self.__maxprice = price c = Computer() c.sell() # change the price c.__maxprice = 1000 c.sell() # using setter function c.setMaxPrice(1000) c.sell()
  • 13. Polymorphism Polymorphism is an ability (in OOP) to use a common interface for multiple forms (data types). Suppose, we need to color a shape, there are multiple shape options (rectangle, square, circle). However we could use the same method to color any shape. This concept is called Polymorphism. class Parrot: def fly(self): print("Parrot can fly") def swim(self): p 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() # passing the object flying_test(blu) flying_test(peggy)
  • 14. File Objects in Python
  • 15. Files Files are named locations on disk to store related information. They are used to permanently store data in a non-volatile memory (e.g. hard disk). Since Random Access Memory (RAM) is volatile (which loses its data when the computer is turned off), we use files for future use of the data by permanently storing them. When we want to read from or write to a file, we need to open it first. When we are done, it needs to be closed so that the resources that are tied with the file are freed. Hence, in Python, a file operation takes place in the following order: 1. Open a file 2. Read or write (perform operation) 3. Close the file
  • 16. 1 . Python File Open - The key function for working with files in Python is the open() function. The open() function takes two parameters; filename, and mode. There are four different methods (modes) for opening a file: 1. "r" - Read - Default value. Opens a file for reading, error if the file does not exist 2. "a" - Append - Opens a file for appending, creates the file if it does not exist 3. "w" - Write - Opens a file for writing, creates the file if it does not exist 4. "x" - Create - Creates the specified file, returns an error if the file exists Syntax - f = open("demofile.txt") f = open("demofile.txt", "rt")
  • 17. Mode Description r Opens a file for reading. (default) w Opens a file for writing. Creates a new file if it does not exist or truncates the file if it exists. x Opens a file for exclusive creation. If the file already exists, the operation fails. a Opens a file for appending at the end of the file without truncating it. Creates a new file if it does not exist. t Opens in text mode. (default) b Opens in binary mode. + Opens a file for updating (reading and writing)
  • 18. 2 . Python File Read - 1. The open() function returns a file object, which has a read() method for reading the content of the file: Example f = open("demofile.txt", "r") print(f.read()) 2. If the file is located in a different location, you will have to specify the file path, like this: Example f = open("D:myfileswelcome.txt", "r") print(f.read()) 3. By default the read() method returns the whole text, but you can also specify how many characters you want to return: Example f = open("demofile.txt", "r") print(f.read(5))
  • 19. 3 . Python Write/Create File - 1. Write to an Existing File To write to an existing file, you must add a parameter to the open() function: "a" - Append - will append to the end of the file "w" - Write - will overwrite any existing content 2. Create a File To create a new file in Python, use the open() method, with one of the following parameters: "x" - Create - will create a file, returns an error if the file exist "a" - Append - will create a file if the specified file does not exist "w" - Write - will create a file if the specified file does not exist
  • 20. Method Description close() Closes the file detach() Returns the separated raw stream from the buffer fileno() Returns a number that represents the stream, from the operating system's perspective flush() Flushes the internal buffer isatty() Returns whether the file stream is interactive or not read() Returns the file content readable() Returns whether the file stream can be read or not readline() Returns one line from the file readlines() Returns a list of lines from the file seek() Change the file position seekable() Returns whether the file allows us to change the file position tell() Returns the current file position truncate() Resizes the file to a specified size writable() Returns whether the file can be written to or not write() Writes the specified string to the file writelines() Writes a list of strings to the file Built –in methods in python
  • 21. Command Line Arguments in Python The arguments that are given after the name of the program in the command line shell of the operating system are known as Command Line Arguments. Python provides various ways of dealing with these types of arguments. The three most common are: 1. Using sys.argv 2. Using getopt module 3. Using argparse module
  • 22. Using sys.argv The sys module provides functions and variables used to manipulate different parts of the Python runtime environment. This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter. One such variable is sys.argv which is a simple list structure. It’s main purpose are: 1. It is a list of command line arguments. 2. len(sys.argv) provides the number of command line arguments. 3. sys.argv[0] is the name of the current Python script.
  • 23. # Python program to demonstrate # command line arguments import sys # total arguments n = len(sys.argv) print("Total arguments passed:", n) # Arguments passed print("nName of Python script:", sys.argv[0]) print("nArguments passed:", end = " ") for i in range(1, n): print(sys.argv[i], end = " ") # Addition of numbers Sum = 0 # Using argparse module for i in range(1, n): Sum += int(sys.argv[i]) print("nnResult:", Sum)
  • 24. Using getopt module Python getopt module is similar to the getopt() function of C. Unlike sys module getopt module extends the separation of the input string by parameter validation. It allows both short, and long options including a value assignment. However, this module requires the use of the sys module to process input data properly. To use getopt module, it is required to remove the first element from the list of command-line arguments. Syntax: getopt.getopt(args, options, [long_options]) Parameters: args: List of arguments to be passed. options: String of option letters that the script want to recognize. Options that require an argument should be followed by a colon (:). long_options: List of string with the name of long options. Options that require arguments should be followed by an equal sign (=). Return Type: Returns value consisting of two elements: the first is a list of (option, value) pairs. The second is the list of program arguments left after the option list was stripped.
  • 25. Using argparse module Using argparse module is a better option than the above two options as it provides a lot of options such as positional arguments, default value for arguments, help message, specifying data type of argument etc. Note: As a default optional argument, it includes -h, along with its long version –help.