Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
221 views

Advance Python

The document discusses various Python concepts like classes, objects, inheritance, exception handling, file handling, logging, multithreading and more. It provides examples of using constructors, variables, methods, access specifiers and polymorphism in classes. Various file operations like read, write, append are demonstrated along with exception handling, logging and multithreading concepts in Python.

Uploaded by

Prafull Sutar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
221 views

Advance Python

The document discusses various Python concepts like classes, objects, inheritance, exception handling, file handling, logging, multithreading and more. It provides examples of using constructors, variables, methods, access specifiers and polymorphism in classes. Various file operations like read, write, append are demonstrated along with exception handling, logging and multithreading concepts in Python.

Uploaded by

Prafull Sutar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 202

Advance Python-

Paradigm - मिसाल(प्रतिमान, pattern, paradigm, parameter, patterned)

Emphasis- जोर
Python Classes/Objects
Python is an object oriented programming language.

Almost everything in Python is an object, with its properties and methods.

A Class is like an object constructor, or a "blueprint" for creating objects.

Class of “a”
Self: -Formal parameter
self-keyword is used to store object reference. We can use other word also but as PEP8
we use standard “self” keyword.
uctors in Python
Constructor :__init__(self).:
A constructor is optional, and if we do not provide any constructor, then Python
provides the default constructor. Every class in Python has a constructor, but it's not
required to define it.

_ _ init _ _ :- method used as a constructor for default assignment.


called Magic method / dendur method.
1. # __INIT__ METHOD USED AS A CONSTRUCTOR FOR DEFAULT ASSIGNMENT.

2.
3.Constructor with 2 obj(objects) But only 1 called .

3.a. 2 obj called


4. constuctor for 1 object multiple values.py

5.
TYPES OF VARIABLE:-

1.Instance variable
_ _ dict _ _ :- to see data available with that object.
Here Double is the local variable which is used within the class.
4.All Variables
2.1Class method Value Change Of class variable
CHECK ORDER OF FUNCTION TO
CALL IT
3.1 Static method
*** All Variables & all Methods
_ _Main_ _:-(Driver code)
For most practical purposes, you can think of the conditional block that you open with if __name__ ==
"__main__" as a way to store code that should only run when your file is executed as a script.

Every code is having their driver code


q
Multilevel Inheritance
MRO-Method Resolution Order
Hierarchical Inheritance
Result of D

Result of E

Result of F

Result of G
Hybrid Inheritance
Super Method
Polymorphism
1.Overloading: -


Method & Constuctor Overriding
Abstraction:-
Access Specifier
1.Public

2.Protected
3.Private
ALL
**MODULE**
EX.1

Import all data


Import with aliasing

CALL MULTIPLE OBJECT

WITH ALIASING
WITH “ * “

1.
2.

“dir” METHOD

“ACCESS WITH MULTIPLE FILES”


FILE HANDLING-
Default Mode-Read mode
*File need to be closed so that other one who need to be use that
File get an access to use of it.
To avoid this there is a line added to neglect developer’s mistakes
with open('TEST1.txt') as fp:
so whenever we run this we’ll get True by default just need to go out of function only.
with open('TEST1.txt') as fp:

data = fp.read()
print (fp.closed)

print (fp.closed)
C:\Users\prafu\venv\Scripts\python.exe
"C:/Users/prafu/PycharmProjects/prafull/ADVPY/PRACTICE/FILE HANDLING/close.py"
False
True

Before this-there was manual close

1.READ MODE
a)read()-file found it return
error-filenotfounderror

Error
Read Desktop file with pathmode-
\\-is compulsory here to get result

To access specific data from list of content

Original file have 6 lines of content-Result gives 5


**Web data access**

b)readlines

For 1st 2 lines only

Only last line


For 1 word of any line-Posional element

C)readline-single call for single line output

DOUBLE CALL-
#sinle time print for 1 line
#double implementation gives 2 lines in result.
d)readable

Convert data into dictionary by using Tuple

2.WRITE MODE
a)write( )

CREADTED NEW FILE WITH CONTENT

RUN AGAINE WITH NEW DATA -RUN & OVERRIDE PREVIOUS DATA
b)Writelines

2.
c)writable-by import

3.Append

Need already available file to process operation in append/else create new file.
a)write( )

Below result look different it has been run twise 1st without \n at ‘ \n asdfgg ‘
b)Writelines

c)Writable
4.Exclusive mode

a)Write mode
if file present return error

If File not created Then create new file

b)Writelines()
c)Writable not possible gives error need new file

5) r+ Mode (read + write mode)

After read( ) - after this command cursor goes to end


position
And
#then write commant start from at end
# where cursor is located after read() command

Tell ( ) – will return the location of cursor( ) 1st it will at 0 position then after read( ) it goes
to last position
**after read() it will return no. of character + spaces available in the given data** so to
check no. of character

Seek( )-To change the position of cursor.


seek + write ( )

Before run

After run
read upto(20) then write n complete read

just add 143000 at end

Read up to (12) then write n complete read.


Here we have data up to 10 digit only
(new data – “1234567890”)
read(18)+seek(18)+write( )

Read (35) +seek (45) + write () data (only up to 35)


6)W+ Mode(write+read) -

Empty File – Already Created

In result we seen nothing coz after w+ mode cursor goes to end position and after that
there is no data remaining to read out.
By using seek( )

7)a+ Mode-(write[append]+read)
*** To create 10 files a time
*@CSV(COMMA SEPARATED VALUES

1a.W MODE(writeline)

TO remove space between line we use Newline


By user

1b.) W MODE ( writerows )


Here in the Pandas it returns complete data so to get data row by row we use csv module.

2)Read(r) mode
r mode -result in row format by function

Csv to csv

Csv to text
Text to Csv

Text to Text

OS MODULE: -
Os.makedirs
-To delete file
_create dir/structure
-change working dir

a) Get current working dir(os.getdir())


b)create dir(os.mkdir())

c)Multiple dir at one go (os. makedirs)


Recursively - वारंवार

d)change dir
From
To

Folder created
at given
location that is
desktop

e) Delete single dir (rmdir-remove dir)

Before
After

e)multiple dir delete(removedirs)


Before

After
single delete of multiple dir by using rmdir

f) Rename

g) multiple delete by function


A. 1st Create
Create dir by function

User input-for change dir & mkdir


User input-for mkdir
User input-for mkdir by function
1.

2.
h)listdir
i)Access any file from anywhere
1.Desktop

** We can access through Cmd also


Tree

date

Time
**EXCEPTION HANDLING-(Unavoidable
condition)
When our logic is currect but due to user input or by condition our logic failed
their we use exception handling
1.Try-contains risky code-The code which may occur error should be written inside the
try block.
When it shows error, it goes to except block.
2.Except-contains handling code
**_in real scenario do not use except like this give proper error names.

Right way to write a code


1)
2)

3)
If file is available

If error not given at except


4.
5. try-except-except(base)
base class of except always need to define at the end
else it can return error
6. Msg of error -slicing
used to get details of error

10/0
#gfdfghokjhg

a=int("45.3")

##Atribute error-is raised when an invalid attribute is made.


This can happen if an attribute or function not associated with a data type is
referenced on it.
6.Try-Except-Finally

try has no error so try and finally


If try is ok then except did not run it directly go to finally

With error
Try(run+error)-Excepy-Finally
Try-Except-else-Finally
****For-else***
If for run perfectly then only else run (friendly nature)
1.Run fail

2.Run successfully
3.Run successfully

4.Run fail
Try inside try
1.
2.
3.
4.
5.
Valid-invalid
**Logger-
5 levels of loggers
Critical-50

Error-40

Warning-30

Info-20

Debug-10

This is the class whose objects will be used in the application code directly to call
the functions.
LogRecords: Loggers automatically create LogRecords objects that have all the
information related to the event being logged, like the name of the logger, the
function, the line no., the message & more.
##Default-
1.message: console
2.level-30&above or warning and above
3.default mode -to store data append mode (we can change the mode of storage
data [file mode])
CRITICAL: root: Critical Message
Level : logger : message
1.Base with Level
Access By Name-
Filename – to store log data

In ‘python32.txt’

****Default mode is Append so data is added with previous data when


we run similar program for 2 times see the result
###To Change the mode
Application:
1.

But our app.log file is empty cause error is not added their so we add
“Logging.error(obj)”
Now the same error we got on a cmd file that we
are added in our app.log file by adding
“logging.error("Exception Details:", exc_info=True)”
Or
2.
Application with error-filename is not found so due to that it will return
Error reduced by passing Try & except

**To trigger log file, we add multiple module log result in an only one file
always.
1.add

2.File handling
3.log

##Basic Configuration format


1. '%(levelname)s'

2.message

3.Asctime (ask time-year-month-date hr-min-sec milisec)

4.datefmt (date format)


d-date, m-month Y-year
Another way

d-date, m-month Y-year I-12 hour M-min S-sec H-24hr

%p for Am & Pm

Above basicConfig can be added to both previous module-filehandling


module
Add module

Error inside the Add.py

Error reduced in except

1. ZeroDivisionError
2. TypeError

Filename inside log- :%(name)s

1.Filehandling.py
2.log.py
3.Add.py

Result-Logger.log
**Assertion:-

-used for testing or debugging purpose


-used as a check-point in program.
-**before/mostly used -use print statement to debug

Assert-condition:-
If true run.
If false stop run.
1.Simple Assert:-
Without Message
With Assertion Error:-
2.Augumented Assert-
Assertion with Message is called Augumented Assert.
**Multithreading:-

Hard core Rule-The code should be independent.


Cored divided into threads.
Remaining code or code remaining from the Thread is run by the * Main
Thread
Main Thread-create thread and run rest of function
Parallel execution-so takes less time to execute the function

Call of main thread


Thread name: -

1.Creating Thread Without using any class


Function Base thread-
Creating thread without using any class with argument-
2. Without extend thread class
3. Without using any class-class base thread

**JOIN Method in Threading


Below here we can clearly say that result is totally based on
th1 and th2 thread but they get run fully main thread
already calculate the result to overcome this we use join.
Join will allow main class to run after execute after the
threads gets fully run their cycle.

Without using join ()


Join-In Python's threading module, the join () method is used to wait for a thread to
complete its execution before continuing with the program. It is particularly useful
when you want to ensure that certain threads have finished their work before
proceeding. Here's how join () is commonly used in threading:
**SERIALIZATION-:
Python Dict to Json String
Indent=4 added :

Store data in the Json format

Json to Python
Store python (dict) data into YAML file format:-
Yaml to python

From Yaml file data to python dict


sort_keys=False
is used to get actual data that we have been inserted
without sorting it.
PICKLING: -

Pickling by user data input


UNPICKLING: -

You might also like