Python
Python
Python
pickling: Converting a Python object hierarchy to a byte stream is called pickling, also referend to as serialization
unpickling: Converting a byte stream to a Python object hierarchy is called unpickling, also referred to as
deserialization
-------------------------------------------------------------------------------------------------------------------------------------------------------
Package is folder with __init__.py file contain different modules each module
Module is .py file or you can say file python code written on it
OOPS
Instantiation is object creation
While initialization is constructor calling
Encapsulation is data hiding and process hiding by making every object private, private is only access through
same class so it is encapsulated to one class
while abstractions are detail hiding
Private is access only through class its value is modified or get by getter setter method.
Protected are marked with single underscore “_” before the name
Private are market with double underscore “__” before the name
Class
Class is blue print for object
attributed is variable in class
Instance is variable in constructor
Function is method in class
Instance is unique for each class object
A change in attribute is shared by all the object of the class
Constructor:
Self keyword stores the instance of class in memory address
Python id return memory address
Constructor initialized the object
Inherited constructor is called only after super keyword is used unlike java where constructor in parent is called
immediately
Super can call on multilevel
Python
Python has 35 keywords
'False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else',
'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return',
'try', 'while', 'with', 'yield'
#Python is a partially compiled language and partially interpreted language. The compilation part is done first
when we execute our code and this will generate byte code internally this byte code gets converted by the Python
virtual machine (PVM)
Python memory
#Python uses its private heap space to manage the memory, all the object are stored in heap memory
#Python also has an inbuilt garbage collector, which recycles all the unused memory and frees the memory and
makes it available to the heap space. A namespace is a naming system used to make sure that names are unique
to avoid naming conflicts.
PEP 8, is a document that provides instructions on how to write Python code. In essence, it is a set of guidelines
for formatting Python code for maximum readability
Variable:
variable name is referenced to the memory address where the value or object is stored
variable can be type casted and is case sensitive
Literal
Type of constant value stored in variable is literal, literals are a notation for representing a fixed value
Numeric, string, bool
Type of Datatype are:
numericType= (int float str),
sequenceType = (list, tuple, range)
mapType = (dict)
setType = (set,frozeset)
boolType = (bool)
bytes
Operators:
algebraic: + ,- ,** ,* ,/, //(floor division return integer)
Comparison: ==, >, !=,< ,<= ,>=
logical: and, or, not
Conditions:
If :
Else :
elif :
is : operator compare the id
in :
and :
or :
not :
ternary operator:
[on_true] if [expression] else [on_false]
expression : conditional_expression | lambda_expr
# dic :
{key: 'value' for (key, value) in iterable }
Functions:
Function is block of code which take some parameters and return some values or objects
Function is first class object can be passed as argument, as key in dictionary, return functions, can be store in data
structure
Higher order function is a function which take function as a parameter
Lambda function is anonymous function accept multiple argument but hold only one expression
Lambda Functions: (lambda arguments: expression)
Lambda function can be immediately invoked: value_stored = (lambda arguments: expression) (val)
lambda function is used with map filter and sort and reduce
Immutable data are passed by value in python function, it sends the copy in parameter
Mutable data are passed by reference in python function any direct change in reference without copying it to any
local variable will affect the original mutable object
Decorators:
a decorator allows you to modify the functionality of a function by wrapping it in another function.
def decorator_name(func):
def inner_func(a,b): # pass parameter in function before passing in function
print("called before function")
func(a,b)
print("called after function")
return inner_func
@decorator_name
def func(a, b):
print(a/b)
Dunder methods and decorators:
Python doesn’t have new keyword for object creation it has __new__ dunder method to instantiate or create
object
Class variable are static in nature it is shared by all the data member
A class method takes cls as the first parameter while a static method needs no specific parameters.
A class method can access or modify the class state while a static method can’t access or modify it.
# Generators
def generator ():
yield 1
yield 2
yield 3
# x is a generator object
x = generator ()
# Iterating over the generator object using next
# In Python 3, __next__()
print(next(x))
print(next(x))
print(next(x))
AsyncIO:
We ran the blocks concurrently giving an impression of parallel execution.
1.Async the function: Define the function async
2.Create a task: Declare the task in task=asyncio.create_task(fn2())
Threading
In threading, we execute one line of code at a time but we constantly change which line is run. Between each
thread so it is not true parallelism but work concurrently line by line in python
Basically, concurrency is switching between two tasks in multiple threads but in python there is always one thread
because of GIL so it switches between line by line
Multiprocessing: is true parallelism however it may fail on decorator, multiprocessing package is used
Context manager:
# - Context Managers
class ContextManager():
def __init__(self):
print('init method called')
def __enter__(self):
print('enter method called')
return self
with take function or class as parameter , after class initialization and __enter__ method it executed then code
inside with are executed after that it run __exit__ , then the print statement is run
Exception handling:
Try:
except:
The raise keyword is used to raise an exception
Else:
#runs when there is no exception raised
Finally:
#runs always after try except it is used as a cleaning up the resources
File handling:
Useful Methods:
swapcase() : It is a string’s function that converts all uppercase characters into lowercase and vice versa.
list.remove(element)
all (Boolean list) : return true if all the iterable item is true
any (Boolean list) : return true if any iterable item is true
Boolean list is made by appending list using if expression and then we check the list with all and any
Monkey patching
sub ()
subn()
Nonlocal
None