Saturday, 22 April 2017

Data Abstraction

Data Abstraction:

  • The concept of hiding the properties of one class from other class  or outside of the class is known as a abstraction or data hiding.
  • Abstraction means hiding the properties of a class.
  • in order to hide the properties of a class we use _ _ beginning of the property/attribute.
  • example: _ _a = 10


class x:
    __a=100
    def display(self):
        print(x.__a)
x_obj=x( )
x_obj.display( )
print(x.__a)

100
Traceback (most recent call last):
  File "E:/python_practice/examples/data abstraction.py", line 7, in <module>
    print(x.__a)
AttributeError: type object 'x' has no attribute '__a'

Note:


  • hidden properties of a class we can access from outside of that class using special syntax.

referenceVariableName._className_ _property/attribute-name


class x:
    __a=100
    def display(self):
        print(x.__a)
x_obj=x( )
x_obj.display( )

print(x_obj._x__a)


100
100

Friday, 21 April 2017

Polymorphism

Polymorphism:

  • the concept of defining multiple functionalities/logic's to perform one operation is known as a polymorphism.
  • poly means -----> many
  • morphism means ------> forms ( functionalities/logic's)


Polymorphism can be implemented in two ways,they are
  • method overloading ( static polymorphism )
  • method overriding ( dynamic polymorphism )

Method Overloading:

  • concept of defining multiple methods with same name with different number.of parameters is known as a method overloading or static polymorphism.
  • when ever we try to implement method overloading concept in python, by default python interpreter recognize recently defined method only.
  • python not support method overloading concept.
class x:
    def m1(self):
        print("i am in single parameter of m1 of class x")
    def m1(self,a):
        print("i am in two parameters of m1 of class x")

x_obj=x( )
x_obj.m1(100)
x_obj.m1( )

i am in two parameters of m1 of class x

Traceback (most recent call last):
  File "E:/python_practice/examples/methodoverloading.py", line 9, in <module>
    x_obj.m1()
TypeError: m1() missing 1 required positional argument: 'a'

  • some people tells python support method overloading with example.
  • i think it is not correct statement.
class x:
    def add(self,instanceOf,*args):
        if instanceOf == 'int':
            result=0
        if instanceOf=='str':
            result=' '
        for i in args:
            result=result+i
        print(result)
x_obj=x( )
x_obj.add('int',10,20,30)
x_obj.add("str",'siva','krishna')


60
sivakrishna

Note:
  • upto my knowledge above example is not a polymorphism.
  • polymorphism means  multiple logics to perform single operation.
  • but above program single logic to perform multiple operations.

Method Overriding:

  • the concept of defining multiple methods with same name with same number.of parameters, one is in super class and another one  is in sub class is known as a method overriding or dynamic polymorphism.
  • when ever super class method is overrided in its sub class always sub class method will be executed if sub class object is created. 
class x:
    def m1(self):
        print("i am in m1 of x class")
class y(x):
    def m1(self):
        print("i am in m1 of y class")
y_obj=y( )
y_obj.m1( )

x_obj=x( )
x_obj.m1( )

i am in m1 of y class
i am in m1 of x class

class x:
    def m1(self):
        print("i am in m1 of x class")
class y(x):
    def m1(self):
        print("i am in m1 of y class")
y_obj=y( )
y_obj.m1( )

i am in m1 of y class

Note: 
  • my requirement is to display both x class(super class) and y class(sub class) statements.
class x:
    def m1(self):
        print("i am in m1 of x class")
class y(x):
    def m1(self):
        super( ).m1( )
        print("i am in m1 of y class")
y_obj=y( )
y_obj.m1( )


i am in m1 of x class
i am in m1 of y class

super( ):
  • super( ) statement is used to call the super class methods or constructor through sub class method or constructor.
Constructor Overriding:
  • the concept of defining multiple constructors with same name with same number.of parameters, one is in super class and another one  is in sub class is known as a constructor overriding
class x:
    def __init__(self):
        self.a=100
class y(x):
    def __init__(self):
        self.b=200
y_obj=y()
print(y_obj.b)
print(y_obj.a)

200
Traceback (most recent call last):
  File "E:/python_practice/examples/constructor overriding.py", line 9, in <module>
    print(y_obj.a)
AttributeError: 'y' object has no attribute 'a'


class x:
    def __init__(self):
        self.a=100
class y(x):
    def __init__(self):
        self.b=200
        super().__init__()
y_obj=y()
print(y_obj.b)
print(y_obj.a)

200
100

Thursday, 20 April 2017

How to Using the properties of one class into another class

How to Using the properties of one class into another class:

We can use the properties of one class into another class in two ways. They are:
  • has-a relationship
  • is-a relationship or inheritance

has-a relationship:-

  • The concept of using the properties of one class into another class by using class name or by using reference variable name is known as a has-a relationship.

class x:
    a=1000
    def __init__(self):
        self.b=2000
    def m1(self):
        print("i am in m1")
    def m2(self):
        print("i am in m2")
class y:
    def display(self):
        print(x.a)
        x_obj=x( )
        print(x_obj.b)
        x_obj.m1( )
        x_obj.m2( )
y_obj=y( )
y_obj.display( )

1000
2000
i am in m1
i am in m2

class x:
    a=10
    def __init__(self):
   self.b=20
    def m1(self):
   print("in m1 of x")
class y:
    c=30
    def __init__(self):
   self.d=40
    def m2(self):
   print(x.a)
   x_obj=x( )
   print(x_obj.b)
   x_obj.m1( )
   print(y.c)
   print(self.d)
   print("in m2 of y")
y_obj=y( )
y_obj.m2( )

10
20
in m1 of x
30
40
in m2 of y

is-a relationship or inheritance:-

  • The concept of using the properties of one class into another class directly is known as inheritance or is-a relationship.
  • A class which is extended by other class is known as a super class or base class or Parent class.
  • A class which is extending another class is known as a sub class or child class or Derived class.
  • super class properties directly accessible to the sub class like as a sub class properties.

class x:
    a=10
    def m1(self):
   print("in m1 of x")
class y(x): 
    c=30
    def __init__(self):
   self.d=40
    def m2(self):
   print(y.a)
   self.m1()
   print(y.c)
   print(self.d)
   print("in m2 of y")
y_obj=y( )
y_obj.m2( )


10
in m1 of x
30
40
in m2 of y

Note:
  • super class properties and sub class properties can be accessed by using subclass name or by using sub class reference variable.

class x:
    a=10
    def m1(self):
   print("in m1 of x")
class y(x):
    c=30
    def __init__(self):
   self.d=40
    def m2(self):
   print("in m2 of y")
   print(y.a)
   print(y.c)
y_obj=y( )
print(y_obj.d)
y_obj.m1( )
y_obj.m2( )

40
in m1 of x
in m2 of y
10
30

class x:
    def __init__(self):
   print("Constructor of x")
    def m1(self):
   print("in m1 of X")
class y(x):
    def m2(self):
   print("in m2 of y")
y_obj=y( )
y_obj.m1( )
y_obj.m2( )

Constructor of x
in m1 of X
in m2 of y

Object:-
  • It is a pre-defined class, which is defined built- in module
  • object class is a super class or base class for every class in python.
  • Object class properties can be accessed directly in every class or we can access through any class reference variable.

class x:
    def m1(self):
   print("in m1 of X")
print(x.__bases__)
x_obj=x( )
print(x_obj)

(<class 'object'>,)
<__main__.x object at 0x00000000034D1E10>

class a:
    pass
print(a.__bases__)
print(dir(object))
help(object)
help(object.__hash__)

Types of Inheritances:-

  • Single Inheritance
  • Multi-level Inheritance
  • Multiple Inheritance
  • Hierarchical Inheritance
  • Cyclic Inheritance

Single Inheritance:-
  • Concept of inheriting the properties from only one class into another class is known as single inheritance.

class X(object):
    """Single Inheritance"""
    def m1(self):
   print("in m1 of X")
x1=X( )
x1.m1( )

in m1 of X

Multi-level Inheritance:-
  • The concept of inheriting the properties from multiple classes into single class with concept of one after another is known as multi-level inheritance.

class X(object):
    """Multi-level Inheritance"""
    def m1(self):
   print("in m1 of X")
class Y(X):
    def m2(self):
   print("in m2 of Y")
class Z(Y):
    def m3(self):
   print("in m3 of Z")
z1=Z( )
z1.m1( )
z1.m2( )
z1.m3( )

in m1 of X
in m2 of Y
in m3 of Z

Multiple Inheritance:-
  • Concept of inheriting the properties from multiple classes into single class at a time is known as multiple inheritance.

class X(object):
    """Multiple Inheritance"""
    def m1(self):
   print("in m1 of X")
class Y:
    def m2(self):
   print("in m2 of Y")
class Z(Y,X):
    def m3(self):
   print("in m3 of Z")
z1=Z( )
z1.m1( )
z1.m2( )
z1.m3( )

in m1 of X
in m2 of Y
in m3 of Z

Hierarchical Inheritance:-
  • The concept of inheriting the properties from one class into multiple classes is known as hierarchical inheritance.

class X(object):
    """Hierarchical Inheritance"""
    def m1(self):
   print("in m1 of X")
class Y(X):
    def m2(self):
   print("in m2 of Y")
class Z(X):
def m3(self):
   print("in m3 of Z")
y1=Y( )
y1.m1( )
y1.m2( )
z1=Z( )
z1.m1( )
z1.m3( )

in m1 of X
in m2 of Y
in m1 of X
in m3 of Z

Cyclic Inheritance:-
  • The concept of inheriting the properties from sub class to super class is known as cyclic inheritance.

Note:-
  • Python does not support cyclic inheritance.
  • in this case object class , object not created,there is no hash code generated.
  • python interprter only takes the hash code value,because of that reason,python not supported cyclic inheritance.

class X(Z):
    """Cyclic  Inheritance is not possible in Python"""
    def m1(self):
   print("in m1 of X")
class Y(X):
    def m2(self):
   print("in m2 of Y")
class Z(Y):
    def m3(self):
   print("in m3 of Z")

z1=Z( )
z1.m1( )
z1.m2( )
z1.m3( )


Traceback (most recent call last):
  File "E:/python_practice/examples/cyclic inhritance.py", line 1, in <module>
    class X(Z):
NameError: name 'Z' is not defined

why the object class is the super class for all classes in python ?

  • python interpreter generates the hash-code(indirect address) based on the original address of the object.
  • after creating the object the original address of the object is taken by the python interpreter,generates the hash code values based on the original address of the object by calling                                       _ _hash_ _( )
  • _ _hash_ _( ) method is present in side the object class because of that reason object class make it has a super class for every class in python.
class a:
    def m1(self):
        print("in m1 of a")
class b(a):
    def m2(self):
        print("in m2 of b")
b_obj=b()
print(b_obj)
print(b_obj.__hash__)           

<__main__.b object at 0x00000000034DC438>

<method-wrapper '__hash__' of b object at 0x00000000034DC438>   

Wednesday, 19 April 2017

Builtin attributes of a class

Builtin attributes of a class :

  • For each and every class in python some attributes/properties are going to be added automatically by the python interpreter.
  • the attributes which are added by the python interpreter are known as builtin attributes/properties.
_ _dict_ _

_ _doc_ _

_ _name_ _

_ _module_ _

_ _bases_ _

_ _weakref_ _



class Test:
    """sample class for builtin attributes"""
    a=100
    def m1(self):
        print("in m1 of test")
print(Test.a)
t1=Test()
t1.m1()
print(Test.__doc__)
print(Test.__dict__)
print(Test.__name__)
print(Test.__module__)
print(Test.__bases__)
print(Test.__weakref__)


100

in m1 of test

sample class for builtin attributes

{'m1': <function Test.m1 at 0x0000000000761400>, 'a': 100, '__doc__': 'sample class for builtin attributes', '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'Test' objects>, '__dict__': <attribute '__dict__' of 'Test' objects>}

Test

__main__

(<class 'object'>,)

<attribute '__weakref__' of 'Test' objects>


Methods:
  • It is possible to define two kinds of methods with-in a class that can be called without an instance.

Class Method:
  • A class method takes cls as first parameter.
  • A class method can access or modify class state.
  • We use @classmethod decorator in python to create a class method.
  • We generally use class method to create factory methods.

Syntax:

class C(object):
    @classmethod
    def fun(cls, arg1, arg2, ...):
       ........................
       ........................
       ........................

Static Method:
  • A static method needs no specific parameters.
  • A static method can’t access or modify it.
  • We use @staticmethod decorator to create a static method in python.
  • We generally use static methods to create utility functions.
Syntax:


class C(object):
    @staticmethod
    def fun( arg1, arg2, ...):
       ....................
       ....................
       ....................

Example:

class Test(object):
    x=20
    def m1(self):
        print"hai,i am in instance method"
        print(Test.x)
 
    @classmethod
    def m2(cls):
        print "hai,i am in class method"
        print(Test.x)
 
    @staticmethod
    def m3():
        print "hai,i am in static method"
        print(Test.x)
 
Test.m2()
Test.m3()
Test.m1()


Monday, 17 April 2017

adding and removing the attributes of a class




  • i can add the attributes and also removing the attributes in any programming languages.

    attributes means static variables(class variable) and non-static variables or object or instance variables.   
     
    Note:
     
    out side the class, we can add the static variables to the class is not possible in Java and .Net. it is possible in Python. 

    Adding the attributes to the class:

    Adding the static and non-static variables to the class and objects.

    We can add the static variables to the class from outside of the class by using class name.

    We can add the non-static variables to the object  from outside of the class by using reference variable.

    The non-static variables which are added to one object cannot access to the other object.

    class X:
        a=10
        def __init__(self):
            self.b=20
    print(X.a)
    x1=X()
    print(x1.b)
    X.c=30
    print(X.c)
    x1.d=40
    print(x1.d)
    x2=X()
    print(x2.b)
    x2.e=50
    print(x2.e)
     
    10
    20
    30
    40
    20
    50
     
    Remove the attributes from the class: 
     
    Deleting the static variables and non-static variables from the class and object:-

    We can remove the static and non-static variables from the class and object by using del keyword

    class X:   
        a=10
        b=20
        def __init__(self):
            self.c=30
            self.d=40
    print(X.a)
    print(X.b)
    x1=X()
    print(x1.c)
    print(x1.d)
    x2=X()
    print(x2.c)
    print(x2.d)
    del X.a
    print(X.b)
    del x1.c
    print(x1.d)
    print(x2.c)
    print(x2.d)

    10
    20
    30
    40
    30
    40
    20
    40
    30
    40


     

Encapsulation

Encapsulation:-

  • Concept of binding or grouping related data members along with its related functionalities is known as Encapsulation

Example:-

For Customer

cname,caadr,caccno and cbal are variables
deposit( ),withdraw( ),transfer( ) and balenq( ) are methods

For Employee

eid,ename,eaddr,esal and email are variables
da( ),ta( ),hra( ),pf( ),tax( ) and tsal( ) are methods

  • class is a syntax of structure is used to grow related data members along with its related functionalities.
  • Implement the Encapsulation practically by using class syntax.


syntax:

class  <class_name>:
             """ doc string """
            ..................
            ..................

            ..................

print("start")
class Test:
""" this is sample class"""
x=10
def m1(self):
print("m1 in Test")
x=Test.x+500
print("end")
t1=Test()
t1.m1()
t1.m1()
t2=Test()
t2.m1()
t2.m1()

start
end
m1 in Test
m1 in Test
m1 in Test
m1 in Test


class Test:
def m1(self):
self.x=10
t1=Test()
t1.m1()
print(t1.x)
t1.x=t1.x+5
print(t1.x)
t2=Test()
t2.m1()
print(t2.x)
t2.x=t2.x+2
print(t2.x)
t3=Test()
t3.m1()
print(t3.x)

10
15
10
12
10

Constructor:-
  • Constructor is a special kind of method , which is used to initialize the non-static variables of a class at the time of creation of the Object.
  • Constructor will be executed automatically.
Syntax:

def  __init__(self, ...):
             -------------------
             -------------------
             -------------------


class X:

    def  __init__(self): -----> constructor
   print("Constructor of X")
    def m1(self):   ---------> method
   print("In m1 of X")
x1=X( )
x1.m1( )


Constructor of X
In m1 of X


class X:
    def __init__(self):
   self.i=10
   self.j=20
    def disp(self):
   print(self.i)
   print(self.j)
x1=X( )
x1.disp( )
x1.i=30
x1.j=40
x1.disp( )
x2=X( )
x2.disp( )
x2.i=50
x2.j=60
x2.disp( )

10
20
30
40
10
20
50
60

class X:
    def __init__(self,i,j):
   self.i=i;
   self.j=j
    def disp(self):
   print(self.i)
   print(self.j)
x1=X(10,20)
x1.disp( )
x2=X(30,40)
x2.disp( )

10
20
30
40

Differences between the method and the Constructor


                 Methods  
            Constructors

Method name can be Anything or any name     
Constructor name should be  _ _init_ _

After creating the object if we call a method then only method will be executed.
Constructor will be executed automatically whenever we created object

with respect to  one object one method can be called for any number of times
with respect to one object one constructor will be executed only once
Methods are used to represent the business logics to perform the operations
Constructors are used to initialize the non-static variables.

why method takes self parameter:

  • when objects are instantiated,the object itself is passed in to the self parameter of the method.


Garbage Collector:-


  • It is a pre-defined program which is present inside python software.
  • Garbage collector removes the unused or unreferenced objects from the memory location. If the reference count of any object is 0(zero) then we call that object as a unreferenced or unused object. 
  • Whenever any object reference count is zero then python interpreter calls the Garbage collector and GC(Garbage collector) removes the object. 
  • After executing the GC more memory is available for the program so that rest of the program execution becomes faster.



class X:

    def  __init__(self):

   print("in constructor of X")

    def  __del__(self):

   print("in destructor of X")

x1=X( )

x2=x1

x2=X( )

x1=X( )


in constructor of X

in constructor of X

in constructor of X

in destructor of X


  • Before going to delete the objects from the memory location it internally executes destructor.
  • _ _del_ _ is known as a destructor.
  • del is a keyword, which is used for removing the attributes.


class X:


    def  __init__(self):

   print("in constructor of X")

    def  __del__(self):

   print("in destructor of X")
x1=X()

x2=X()

x3=X()

del x1

del x2

del x3


in constructor of X

in constructor of X

in constructor of X

in destructor of X

in destructor of X

in destructor of X