Sunday, July 19, 2020

advance python theory

Advance-Python
Table of content:
1.Constructor & Destructors
2.Iterator/Generator/Decorator/Closures
3.OOPS->Classes / Object / Instance
(protective,private &public variable)
Data abstruction / Encapsulation /
Inheritance  (Their types) / Polymorphism
4.Method overriding 
5.Ternary operator
6.Module/Packages





Constructor: Constructors are generally
used for instantiating an object.
The constructor is for initialization of a
class when an object of the class is created.
In Python, the __init__() method is called
the constructor and is always called when
an object is created.

Default constructor :A constructor without
arguments [one reference parameter(self)]

Parameterized constructor :constructor with
parameters(self,abhay,pratap,..)


class ddinfosoft:
aps = ""
# default constructor
def __init__(self):
#Constructor with one arguments or default constructor

self.aps = "abhay"
# a method for printing data members
def print_sharma(self):
print(self.aps)
# creating object of the class
obj = ddinfosoft()
# calling the instance method using the object obj
obj.print_sharma()
-------------------------------------------------------------
class Addition:
    first = 0
    second = 0
    answer = 0
    # parameterized constructor
    def __init__(self, f, s):
Constructor With parameter 
        
self.first = f
        self.second = s
def display(self):
        print("First number = " + str(self.first))
        print("Second number = " + str(self.second))
        print("Addition of two numbers = " + str(self.answer))
    def calculate(self):
        self.answer = self.first + self.second
   # this will invoke parameterized constructor
obj = Addition(1000, 2000)
obj.calculate()
# display result
obj.display()
-------------------------------------------------------------
Destructors : an object gets destroyed,
The __del__() method is a known as a
destructor method in Python.
*It is called when all references to the object
have been deleted i.e when an object is a
garbage collected.
def __del__(self):
  # body of destructor

Iterator-
An iterator is an object that contains
a countable number of values &
iterates upon all the values which
implement the iterator protocol,
which consists of the methods
__iter__() and __next__().

Tuples are iterable, in exactly the
same manner as lists.
Since a tuple is iterable,
a mutable copy is easily created
using the list().

Ex:
list=[1,2,3,4,5]
list.iter()
print(next(list))
print(next(list))
print(next(list))


Iterator v/s for loop?
Iterator remembers the previous value then
print the next value by using ‘iter’ and ‘next’
the method, so it consumes more memory
than ‘for’ loop.

But, when you once apply ‘for’ loop in
anything it iterates upon all values at a time
and doesn’t remember the previous value,
so it uses less memory over an iterator
(just like mutable v/s immutable list & tuple).

Generator-
Generators are used to create iterators,
but with a different approach.
Generators are simple functions that return
an iterable set of items, one at a time,
in a special way. When an iteration over a
set of items starts using the for the
statement, the generator is run.
*We used the ‘yield’ method for the
generator to print the maximum number of
output according to code.


def topten():
n=1
while n <=10:
sq=n*n
n+=1
yield sq
for i in values:
values=topten()
print(i)

-------------------------------------------------------------
Decorator-
A decorator is a design pattern in Python
that allows a user to add new functionality
to an existing object without modifying its
structure. Decorators are usually called
before the definition of a function, you want
to decorate.
*A decorator is used to wrap the function.
*It gives new functionality without changing
the original functions.
* @func_name used for the function to be
decorated.


class student:

def __init__(self, name, grade):
self.name = name
@property
self.grade = grade def msg(self):
@msg.setter
return self.name+"got grade"+self.grade def msg(self,msg):
self.grade=sent[-1]
sent = msg.split(" ") print(sent) self.name=sent[0]
print("grade:",stud1.grade)
stud1 = student("nia" , "B") stud1.msg = "abhay got grade A" print("name:",stud1.name)
print(stud1.msg)


Closures-A Closure is a function object
that remembers values in enclosing scopes
even if they are not present in memory.
It is a record that stores a function together
with an environment: a mapping associating
each free variable of the function
(variables that are used locally but defined
in an enclosing scope) with the value or
reference to which the name was bound
when the closure was created.
A closure—unlike a plain function—allows
the function to access those captured
variables through the closure’s copies of
their values or references, even when the
the function is invoked outside their scope.

# Python program to illustrate 
# closures 
def outerFunction(text): 
text = text 
def innerFunction(): 
print(text) 
return innerFunction # Note we are returning function WITHOUT parenthesis 
if __name__ == '__main__': 
myFunction = outerFunction('Hey!') 
myFunction() 

*As observed from above code, closures
help to invoke function outside their scope.
*The function inner function has its scope
only inside the outer function. But with the
use of closures, we can easily extend its
scope to invoke a function outside its scope.
When and why to use Closures:*As closures
are used as callback functions, they provide
some sort of data hiding. This helps us to
reduce the use of global variables.
*When we have few functions in our code,
closures prove to be an efficient way. But if
we need to have many functions, then go for
class (OOP).

-------------------------------------------------------------
Classes: Classes are created by keyword
class.
Attributes are the variables that belong to
the class.
Attributes are always public and can be
accessed using the dot (.) operator. Eg.:
Myclass.Myattribute
Object: An Object is an instance of a Class.
An object consists of :
State: It is represented by attributes of an
object. It also reflects the properties of an
object.
 the response of an object with other objects.
Identity: It gives a unique name to an object
and enables one object to interact with other
objects.
Behavior: It is represented by methods of
an object. It also reflects.

_var:Befor Single underscore with variable  => Protective

__var:Before double underscore with variable  => private

__var__:Before and after double undersocre with variable => Public


Public Method: Accessible from anywhere
Private Method: Accessible only in their own class,(__)start with a double underscore
Public Variable: Accessible from anywhere 
Private Variable: Accessible only in their own class,(__)start with a double underscore

# A Sample class with init method

class Person:

    # init method or constructor

    def __init__(self, name):
        self.name = name

# Sample Method
    def say_hi(self):
        print('Hello, my name is', self.name)


obj = Person('abhay')

obj.say_hi()

-------------------------------------------------------------
Data abstraction: Abstraction means hiding
the complexity and only showing the
essential features of the object. A class that
contains one or abstract methods are called
an abstract class.
e.g:
from abc import ABC, abstract method
class A(ABC):
    def display(self):
        None
class B(A):
    def display(self):
        print("this is display method")

obj=B()
obj.display()

Encapsulation: Encapsulation using
oop’s in python, we can restrict to method
& variables. This prevents data from direct
a modification which is called encapsulation.
we denote protected attribute using an
underscore as prefix i.e single “_” or
double underscore used for the private
attribute. 


*Encapsulation involves packaging one or
more components together.
*Encapsulation is a process wrapping data
and related behavior together into a single
unit .eg. the capsule that is mixed with
several medicines.
*Encapsulation is defined as the process of
enclosing one or more items within a
physical or logical package.
*We can create a fully encapsulated class by
making all the data members (variable)
private. Now we can use the setter and
getter method to set and get the data in it.

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()
c.__maxprice = 1000  # change the price
c.sell()
c.setMaxPrice(1000)  # using setter function
c.sell()
-------------------------------------------------------------

Inheritance: Inheritance allows us to
define a class that inherits all the methods
and properties of another class. The parent
class is the class being inherited from, also
called a base class. The child class is the
class that inherits from another class, also
called derived class.

Single Inheritance:
when a single Subclass is inherited from a
single superclass then the inheritance is
called single inheritance.



Class A:
statements
Class B(A):
statements

Multi-Level Inheritance:
when a subclass is inherited from another
subclass, then that inheritance is called as
multi-level inheritance.


Class A:
statements
Class B(A):
statements
Class C(B):
statements


Multiple Inheritance: when
The subclass is inherited from more
than one superclass then,
inheritance is called multiple inheritances.


Class A:
statements
Class B:
statements
Class C(A,B):
statements
Hierarchical Inheritance:When two child class
inherite property of parent class is called
hierarchical inheritance.


Class A:
statements
Class B(A):
statements
Class C(A):
statements
Hybrid Inheritance: Any combination
of single, hierarchical,
and multi-level inheritances is called
as a hybrid inheritance.

Class A:
Statements
Class B(A):
Statements
Class C(A):
Statements
Class D(B,C)

statements



# This demo is for Single Level Inheritance
class Parent:
    def __init__(self):
        print("I am the Parent Constructor")
    def display(self):
        print("I Provide Black And White Color")
class Child(Parent):
    def __init__(self):
        # super().__init__()
          print("I am the Child Constructor")

  def myMethod(self):

        print("Beep Beep")

obj = Child()

obj.display()
obj.myMethod()


# This demo is for Hierarchical Inheritance
class Animal:
    def move(self):
        print("I move therefore I am...")
class Human(Animal):
    def move(self):   #Overriding
        print("Humans can walk and run...")
class Fish(Animal):
    def move(self):   #Overriding
        print("Fishes can swim and dive...")
def main():
    h1 = Human()
    h1.move()
    f1 = Fish()
    f1.move()
if __name__ == "__main__":
    main()


--------------------------------------------------------------------------------------------------------------------------
# This demo is for Multiple Inheritance
class MySuperClass1():
    def method_super1(self):
        print("method_super1 method called")
class MySuperClass2():
    def method_super2(self):
        print("method_super2 method called")       
     
class ChildClass(MySuperClass1, MySuperClass2):
    def child_method(self):
        print("This is child method")      
c = ChildClass()
c.child_method()
c.method_super1()
c.method_super2()


--------------------------------------------------------------------------------------------------------------------------
Polymorphism: Polymorphism is an
ability (in oop) to use a common interface
for multiple forms (data types).
Polymorphism means having many forms
and in Python, it means having a method
(with the same name) indifferent classes
through method overriding.
This allows a function to use the objects of
these classes and call the overridden method,
without having to worry about the actual
types of objects. The definition of the method
to be invoked is determined at runtime,
based on the type of the object.

# Python - Polymorphism in Python
# Base class
class Fruit:
    def message(self):
        print('Eat Fruits')
# Derived class
class Apple(Fruit)  
    # method message() of base class Fruit is overridden 
    def message(self):
        print('Eat Apples')
# Creating an object of Fruit
ob_fruit = Fruit()
# Creating an object of Apple
ob_apple = Apple()
# Creating a list of objects
a_list = [ob_fruit, ob_apple, ob_apple, ob_fruit]
# Using a for loop to iterate through a list of objects in list i.e.  a_list
for ob in a_list:
    ob.message()

Method overriding:
Overriding in Python. ... It means that one of the methods overrides the other. If there is any method in the superclass and a method with the same name in a subclass, then by executing the method, the method of the corresponding class will be executed.

class parent:
    name="Scott"
‘’’ Latest value will be overridden that value Will be printed, also called as latest method’’’

class child(parent):
    name="David"
obj=child()
print(obj.name)
class Bank:
    def rate_of_interest(self):
        return 0
class ICICI(Bank):
    def rate_of_interest(self):
        return 10.5
obj=ICICI()
print(obj.rate_of_interest())

-------------------------------------------------------------
Ternary operator: A operator that perform
the operation over three value by using
if-else condition is called as ternary
operator.
a=10
b=20
c=30 if a>b else 40   # c=first_value if
condition else second value
print(c)
output=40



Module/Packages: Module is a file that
contains various Python functions and also
global variables. It is simply just a .py
extension file that has python executable
code. On the other hand, Package is nothing
but a collection of modules. It must
contain __init__.py file to let the python
interpreter know this is not just a simple
directory but a collection of modules or
packages. Basically, you don’t have to write
anything in the __init__.py file but must be
there in the module directory.
A library is just a collection of related
functionality. Nothing more, but also
nothing less. The defining characteristic of
a library is that you are in control, you call
the library.

Library > Packages > Modules > Functions
or class or method


library: a collection of related functionality
framework: Inversion of Control
module: abstract interface with explicit
exports and imports, implementation and
interface are separate, there may be multiple
implementations and the implementation is
hidden.
E.g.
module = your fingers>and some functions.
library = your hand's
framework = your body










5 comments: