You are on page 1of 8

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

Abstraction: An abstract class can be considered as a blueprint for other classes.


class or method can’t be instantiated but they can be access only with inheriting it,
abstract and interface keyword is used in java
While in python to make abstract class we need to sub the class with abc module
#An Abstract cannot be instantiated; we cannot create objects for the abstract class.
# it has to be inherited and method should be overridden

Inheritance in java is achieved by extend keyword


While in python it is achieved by subclassing it

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

Polymorphism is method overloading and overriding and operator loading


Python support all
Operator overloading is achieved by dander method
Constructor overloading in not possible in python

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

super (). __init__ (id, name, Add)


child object can access parent and child class properties
Super is used to call methods from parent class in child without calling their name

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 High level programming language


Interpreted language it executes code line by line and stop if error occur

Dynamically typed: datatype is not needed to define in code.


Statically typed: datatype is definition is must

#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

""" docstring '""" used as a comment

identifier is name of the variable, class, function, objects and modules

Namespace is the name collection in different scope in python


1.enclosed (inside nested function)
2.local (inside function)
3.global (inside module and outside function)
4.built-in (outside module)
lifecycle of namespace depends on the scope of the variable and object

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

Mutable and Immutable


Immutable can’t be changed but rather reassigned by defining newly
str, int, float, bool, tuple, frozeset

Mutable: can be changed modified


list, set, Dict
List store multiple type of datatype while array store only single type of data

Iteration and Iterables:


Iterable is a sequential object which can be looped or iterate over
1. for i in iterable
2.while(condition)
Note:
 While is used for looping feature in python
 for is used for iterate through iterable
 iter is method, iterable is python object
 zip () function returns a zip object, which maps a similar index of multiple containers.
 Break statement in Python is used to bring the control out of the loop
 The Python pass statement is a null statement. i.e., there is no operation
 comment is ignored by the interpreter
 continue: it forces to execute the next iteration of the loop.

# python code to demonstrate working of items ()


d = {"geeks": "for", "only": "geeks"}
# iteritems() is renamed to items() in python3
# using items to print the dictionary key-value pair
print("The key value pair using items is : ")
for i, j in items():
print(i, j)
Comprehensions
# list comprehension: it is a way to write compact codes.
 Normal: [expression for variable in iterable]
 If: [expression for variable in iterable if condition]
 Nested If: [expression for variable in iterable if condition if conditions]
 If-else: [expression if condition else expression for variable in iterable ]
ternary operation: (true if condition else false)

# dic :
{key: 'value' for (key, value) in iterable }

Tuple comprehension is not possible

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

Global: is used to modify variable out of the scope

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:

__init__ is the object initializer constructor method

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.

There are only 3 builds in decorator in python


@classmethod
@staticmethod
@property

Generator and iterator:


iterator is an object allows to traves through data without storing data in memory
Generator is a Function returning iterator object using yield
 Yield doesn’t not end the function it pauses and return the current loop value, so next time again it is
called it resume from the next value, generator function return and iterator object, iterator object are
called with next function
 Iterable object are converted into iterator using iter method
 next () keyword is used to call the next element in the iterator object.

# Generators
def generator ():
yield 1
yield 2
yield 3

# Driver code to check above generator function


for value in generator ():
print(value)

# 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))

Iterator objects are exhausted if its called completely

Map, Filter and sort


Basics of MAP, FILTER
They are higher order function
It takes an iterable and function in parameter
Return iterator object in return
All the return object are type casted to their respective datatype
map: map (function, iterable1, iterable2) create a new list with value returning from the function
filter: filter (function, iterable): filter parameter function should have if condition and return true or false
reduce: functool.reduce(function,iterable) :take 2 value of iterable, reduce and return list to a single value

Basic of sorted and sort:


applied on iterable to sort in ascending and descending order
they take key function and reverse as parameter
sort: iterable.sort(key = function, reverse: True/false)
sorted: sorted (iterable , func, reverse: True/false)
sorted create new list while sort modify the list
sort by default rearrange it to ascending order

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())

Create a structure of asynchronous structure using await


3. Every time you call “await asyncio.sleep(1) ” it will switch to the other task It will switch
4. To run a asynchronous function “asyncio.run(fn())”

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

def __exit__(self, exc_type, exc_value, exc_traceback):


print('exit method called')

with ContextManager() as manager:


print('with statement block')

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

Debugging and testing:


assert: used in debugging if condition returns False, AssertionError is raised

Assert expression, assertion_message

File handling:

With function_name as alias_name:


alias.operation

Useful Methods:

swapcase() : It is a string’s function that converts all uppercase characters into lowercase and vice versa.

strip: return list from string


iterable.Strip (““): remove space in string
lstrip: remove leading spaces in string

join: return list item to string


“sperator”. join(iterable): take all item in iterable and joins them in one string

Enumerate is used for indexing the iterable in loops


Enumerate () method adds a counter to an iterable and returns it in a form of enumerating object.
Enumaurate(iterable) fetch key only for index counter
Enumaerate(iterable.value()) fetch value in key value pair in counter
Enumaerate(iterable.items()) fetch both key value
Xrange : Whenever the xrange() function is invoked, the generator object is created by the function and returned.
range: a sequence of numbers is created by the function and returned iterator object

Slicing: Lst[ Initial : End : IndexJump ]

list.remove(element)

del list[start:end] #create a new list

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

Id(object) : is used to watch memory address


Dir() is used to check local, global, inbuilt and enclosed level names
Match: case is switch: case in python introduce recently

Monkey patching

sub ()
subn()

Nonlocal
None

You might also like