SlideShare a Scribd company logo
1 of 90
Download to read offline
BipinRupadiya.com 1
BipinRupadiya.com
GUJARAT TECHNOLOGICAL UNIVERSITY
MASTER OF COMPUTER APPLICATIONS (MCA)
SEMESTER: III
Subject Name: Programming in Python
Subject Code : 4639304
2
BipinRupadiya.com
Unit-3
 Classes and Object-oriented Programming:
 Chapter-13: Classes:
 Chapter-14: Inheritance and Polymorphism:
 Chapter-15: Abstract Classes and Interfaces:
3
Text Book:
R Nageswara Rao, Core Python Programming, 2nd Edition, Dreamtech Press
BipinRupadiya.com
Python
Chapter-13
Classes
Creating a Class, The Self Variable, Constructor, Types of
Variables, Namespaces, Types of Methods (Instance Methods,
Class Methods, Static Methods), Passing Members of One Class to
Another Class, Inner Classes
BipinRupadiya.com
Class
 Class is a model or blueprint to create objects.
 We write class with attributes and actions of objects.
 Attributes are represented by variables
 Actions are performed by methods.
 So a class contains methods and variables.
 Same methods and variables are also available in objects, as they
are created from class.
 The variables which are created inside the inside the instance (i.e
object) are also called instance variable.
BipinRupadiya.com
Difference between function and methods
 A function inside a class is known as method.
 Method is called using two ways.
 classname.methodname()
 Instancename.methodname()
BipinRupadiya.com
Class
 Syntax :
Class Classname(object):
attributes
def _init_(self):
def method1():
def method2():
 All classes have a function called __init__(), which is always
executed when the class is being initiated.
 Use the __init__() function to assign values to object properties, or
other operations that are necessary to do when the object is being
created.
 Here _init_ is the special method to initialize the variable
BipinRupadiya.com
Class
name ,age, marks variables
def _init_(self)
def talk(self)
s1=self
BipinRupadiya.com
The Self variables
 Self is default variable that contains memory address of the instance of the
current class.
 So we can use self to refer all instance variable and instance methods.
 When instance to the class is created, the instance name contains the
memory location of the instance.
 This memory location is internally passed to self.
 We use self in two ways:
 def _init_(self)
 Here self can be used to refer to the instance variable inside the
constructor
 def talk(self)
 Self can be used as first parameter in the instance method.
BipinRupadiya.com
Constructor
 Constructor is special method that is used to initialize the instance variable of a
class.
 In a constructor, we create the instance variable and initialize them with some
starting values.
 For example:
 def __init__(self):
self.name = “bipin”
self.marks = 60
 a constructor is called at a time of creating an instance.
S1 = Student()
 We can write constructor with some parameters too.
 def __init__(self, n=‘ ‘ , m=0)
 s1 = Student(‘bipin’, 64) //calling
BipinRupadiya.com
Constructor
OUTPUT
Name : bipin
Mark : 60
BipinRupadiya.com
Types of parameter
 The variables which are written inside a class are of two types:
 Instance Variable
 Instance variable are the variables whose separate copy is created
in every instance.
 Class Variable or Static Variables
 In class method contain first parameter default as ‘cls’ with which
we can access class variable.
 So to access class variable , we need class method with first
parameter as ‘cls’.
BipinRupadiya.com
Example
13
OUTPUT
roll no : 1
Name : bipin
Mark : 60
roll no : 2
Name : hitesh
Mark : 62
BipinRupadiya.com
Namespace
 Namespace represents, a memory block where names are
mapped(or linked ) to objects.
 For example n=10
 Name n is linked to 10 in Namespace.
 A class maintains its own namespace called ‘class namespace’.
 in the class namespace names are mapped to class variables.
 In the instance namespace, the names are mapped to instance
variables.
BipinRupadiya.com
Types of method
 The purpose of method is, to process the variable of class in the
method.
 The variable declared in the class are called class/static variables.
 The variable declared in the constructor are called instance
variables.
 Types of method exist:
 Instance method
Accessor method
Mutator method
 Class methods
 Static methods
BipinRupadiya.com
Instance method
 This type of methods act upon the instance variable of the class.
 Instance method are bound to instance/objects.
 Instancename.method()
 Since instance variable are available in the instance, instance method need to know
the memory address of the instance.
 This provided through ‘self’ variable by default as first parameter.
 Instance methods are of two types:
 Accessor method (getter method-getxxx())
 Accessor method simply access or read the data, it does not modify data or
variables.
def getName(self):
return self.name
 Mutator method(setter method-setxxx())
 Mutator method can also modify the data.
def setName(self, name):
self.name = name
BipinRupadiya.com
Class method
 These methods act on class levels.
 Class methods are the methods which act on class variables or
static variables.
 These methods are written using @classmethod decorator
above them.
 By default first parameter for class is cls which refers to class
itself.
 Format to refer class variable
 cls.var
 Method calling
 Classname.method()
BipinRupadiya.com
Example
18
OUTPUT
Roll No : 1
Name : bipin
Mark : 63
Roll No : 2
Name : bipin
Mark : 63
BipinRupadiya.com
Static method
 A static method is also a method which is bound to the class and not
the object of the class.
 A static method can’t access or modify class state
 Static method can be use for Example,
 setting environmental variables,
 counting the numbers of instance of the class or
 changing an attribute in another class,
 etc, are the task related to class, that handles by the static methods.
 Also , static methods can be used to accept some values, process them
and return the result.
 Static methods are written with decorator @staticmethod above them.
BipinRupadiya.com
Static method example
OUTPUT
Roll No : 1
Name : bipin
Mark : 63
Roll No : 2
Name : bipin
Mark : 63
BipinRupadiya.com
Class method vs Static Method
 A class method takes cls as first parameter while a static method needs no specific
parameters.
 A class method can access or modify class state while a static method can’t access
or modify it.
 In general, static methods know nothing about class state. They are utility type
methods that take some parameters and work upon those parameters. On the
other hand class methods must have class as parameter.
 We use @classmethod decorator in python to create a class method and we use
@staticmethod decorator to create a static method in python.
 When to use what?
 We generally use class method to create factory methods. Factory methods
return class object ( similar to a constructor ) for different use cases.
 We generally use static methods to create utility functions.
21
BipinRupadiya.com
Passing
members of one
class to another
class
 It is possible to pass the
members(i.e. attributes and
methods) of a class to
another class.
Roll No : 1
Name : bipin
Mark : 60
Roll No : 2
Name : bipin
Mark : 63
bipin is Pass
BipinRupadiya.com
Inner class
 Writing a class within another classis known as inner class or nested class.
 If we write a class B inside another class A, then B is known as inner class.
 If an object is created using a class, the object inside the root class can be
used.
 A class can have more than one inner classes, but in general inner classes
are avoided.
BipinRupadiya.com
Inner class
BipinRupadiya.com
Inner class
Name : Mr. abc
DOB : 1/2/12
BipinRupadiya.com
Inner class
Name : Mr. abc
DOB : 1/2/12
BipinRupadiya.com
Python
Chapter-14
Inheritance and Polymorphism
Constructors in Inheritance, Overriding Super Class Constructors and Methods,
The super() Method, Types of Inheritance, Single Inheritance, Multiple
Inheritance, Method Resolution Order (MRO), Polymorphism, Duck Typing
Philosophy of Python, Operator Overloading, Method Overloading, Method
Overriding
BipinRupadiya.com
Basic Inheritance
 Code / software re-use is considered one of the golden
rules of object-orientated programming.
 By using generalization we eliminate duplicated code
whenever possible.
 One mechanism to achieve this is inheritance
 when one subclass can leverage code from another
base class.
BipinRupadiya.com
What Is Inheritance?
 Inheritance is when a class uses code constructed within
another class. If we think of inheritance in terms of
biology, we can think of a child inheriting certain traits
from their parent. That is, a child can inherit a parent’s
height or eye color. Children also may share the same last
name with their parents.
 Classes called child classes or subclasses inherit
methods and variables from parent classes or base
classes.
BipinRupadiya.com
Basic Inheritance
 Technically all classes are a sub-class of a class called
Object, so they all inherit from that class.
 The class called Object doesn’t really have many
attributes or methods, but they give all other classes
their structure.
 If a class doesn’t explicitly inherit from any other class it
implicitly inherits from Object.
BipinRupadiya.com
Basic Inheritance
We can explicitly call the Object class as follows:
BipinRupadiya.com
Basic Inheritance
 A python program to create a Teacher class and store it into teacher.py
BipinRupadiya.com
Basic Inheritance
 Python program to use Teacher class …..name of file is Ch14-P2.py
1
Bipin
BipinRupadiya.com
Basic Inheritance
 Now if we want to
use data of
Teacher class in
other program at
that time code
Reusability
concept comes.
Write below code
on file
12
Bipin
99
BipinRupadiya.com
Basic Inheritance
 So Inheritance Syntax is given below:
class SubClass(BaseClass)
class Student(Teacher) //example of it
BipinRupadiya.com
Constructors in Inheritance
 Constructor from super class is inherited in base class.
 See below example for that.
BipinRupadiya.com
Overriding
Super Class Constructor and Methods
 When the subclass’
constructor is
replacing the super
class constructor that
is called constructor
overloading.
 When the subclass’
method with same
name as super class
is replacing the super
class method that is
called method
overloading.
BipinRupadiya.com
The Super Method
 Super is built in method which is used to call the super class constructor or method.
 Any constructor written in the super class is not available to the sub class if the sub
class has an constructor.
 So how can we initialize the super class instance variables and use them in sub class?
 Using super()
BipinRupadiya.com
Types of the Inheritance
 Main advantage of inheritance is class reusability.
 All classes in python are built from super a single super class called ‘object’.
 If a programmer will create his own classes, by default object class will
become super class for them internally.
 Syntax:
class Childclass(Parent class):
class Myclass(object):
 Types of inheritance,
1. Single Inheritance
2. Multiple Inheritance
3. Multilevel inheritance:
4. Hierarchical inheritance
5. Hybrid inheritance:
BipinRupadiya.com
Types of the Inheritance
1. Single inheritance: When a child class inherits from only one parent
class, it is called as single inheritance. We saw an example above.
2. Multiple inheritance: When a child class inherits from multiple
parent classes, it is called as multiple inheritance.
Unlike Java and like C++, Python supports multiple inheritance. We
specify all parent classes as comma separated list in bracket.
3. Multilevel inheritance: When we have child and grand child
relationship.
4. Hierarchical inheritance More than one derived classes are created
from a single base.
5. Hybrid inheritance: This form combines more than one form of
inheritance. Basically, it is a blend of more than one type of inheritance.
40
BipinRupadiya.com
Types of the Inheritance
41
BipinRupadiya.com
Single Inheritance
 When a child class inherits from only one parent class, it is called as single
inheritance.
A
B
BipinRupadiya.com
Multiple inheritance:
 When a child class inherits
from multiple parent classes,
it is called as multiple
inheritance.
43
A B
C
BipinRupadiya.com
Problem In Multiple Inheritance
c : 30
b : 20
c : 30
a : 10
BipinRupadiya.com
Problem In Multiple Inheritance
 Problem is the Class C is
Unable to access
construction of both the
super classes.
 It means C class cant
access all the instance
variable of both of its
super class.
 If C class wants to access
instance variable of both
of its super classes then
the solution is to use
super().__init__ () in
every class. c : 30
a : 10
b : 20
BipinRupadiya.com
Method Resolution Order(MRO)
 In multiple inheritance, any specified attribute or method is searched first in the
current class.
 If not found, the search continues into parent classes in depth first, in left to
right manner without searching the same class twice.
 Searching in this way is called Method Resolution order (MRO)
 That’s the reason in previous example we get, output like c,a,b.
 Three principles followed by MRO:
1. Search the subclass before going for its base classes.
2. When a class is inherited from several classes then it searches in order of left to
right in the base class.
3. It will not visit any class more than once.
To know about MRO , we can use mro() method as:
classname.mro()
BipinRupadiya.com
Method Resolution Order(MRO)
 Use mro() method on class P
 Syntax:-
print(P.mro())
c : 30
a : 10
b : 20
[<class '__main__.C'>,
<class '__main__.A'>,
<class '__main__.B'>,
<class 'object'>]
BipinRupadiya.com
Multi Level Inheritance
48
A
B
C
When we have child and grand child relationship. It is known as multilevel inheritance
c : 30
b : 20
a : 10
BipinRupadiya.com
Hierarchical inheritance
49
More than one derived classes are
created from a single base it is
known ad Hierarchical inheritance
c : 30
a : 10
------
b : 20
a : 10
B C
A
BipinRupadiya.com
Hybrid inheritance:
50
This form combines more than one form of
inheritance. Basically, it is a blend of
more than one type of inheritance.
d : 40
b : 20
c : 30
a : 10
B C
A
D
BipinRupadiya.com
Polymorphism
 It comes from Greek word poly means many and morphism means form.
 If something exhibits various forms then it is called polymorphism.
 In programming, polymorphism means same function name (but different
signatures) being uses for different types.
BipinRupadiya.com
Polymorphism
 In programming, a variable , object or method will also exhibits the
same nature as of the sound.
 A variable may store a different types of data, object may exhibit
different behaviours in different context or method may perform
various tasks in python.
 This type of behaviour is called polymorphism.
 Definition:
If a variable, object or method exhibits different behaviour in
different context, it is called as polymorphism.
BipinRupadiya.com
Example of polymorphism
1. Duck typing philosophy of python
2. Operator overloading
3. Method overloading
4. Method overriding
BipinRupadiya.com
Duck typing philosophy of python
 Python variable are name or tags that point to memory
location where data is stored.
 Python’s type system is strong because every variable and
object has type that can be check through type() function.
 Python’s type system is dynamic since type of variable is
not explicitly is declared. But it changes with the content
being stored.
 Example
 x=10 will take int type
 later if you define x=‘hello’ will take str type
BipinRupadiya.com
Duck typing philosophy of python
Python’s duck typing,
a special case of
dynamic typing,
uses techniques
characteristic of
polymorphism,
including
late binding and
dynamic dispatch”
BipinRupadiya.com
Duck typing philosophy of python
 Similarly , if we want to call a method on an object and
we don’t need to check the type of an object , and we
don’t want to know weather this method is actually
belong to that object or not.
 So for this use below code:
def call_talk(obj):
obj.talk()
 The call_talk method is receiving an object ‘obj’ from outside
and using this object, it is invoking(or calling) talk() method.
 It is not required to mention the type of an object ‘obj’ or to
check weather the talk() method belongs to that object or not.
BipinRupadiya.com
Problem:
 If method does not
belong to that object ,
there will be an error
called ‘AttributeError”
BipinRupadiya.com
Duck typing philosophy of python
 So, in python we never worry about the type(class) of
object .
 The object’s type is distinguished only at runtime.
 “so, if it walks like a duck and talks like duck ,it must be
duck”, this principle we follow. This is called duck typing.
BipinRupadiya.com
It is not duck typing…!
checking the object (or
class) type to know
weather the method
exist in the object or
not in this manner
it is called as
‘Strong Typing’
but
it is not duck typing
BipinRupadiya.com
Operator Overloading()
 We know that operators perform an action for example + perform
addition, - perform subtraction …etc
 See in below example + is used for addition of integer , concatenation of
String and to combine two lists.
 So if any operator performs additional operation other than what it is
meant for, it is called operator overloading.
 example of polymorphism
BipinRupadiya.com
Operator Overloading
 If we use + operator to add two object
 It will give error, to do so we need operator overloading
 Example
BipinRupadiya.com
Operator Overloading
Example:
Use of __add__() method to add
the content of objects
+ operator we can use to add the
content of two object
so we are giving additional task to
the ‘+’ operator to add the
content of the object,
which come under operator
overloading concept.
Plus “+” Operator Overload
200
BipinRupadiya.com
Operator Overloading
Grater Than “>” Operator Overload
BookY have more pages
BipinRupadiya.com
Python magic methods or special
functions for operator overloading
 Arithmetic Operators :
 Comparison Operators :
 Assignment Operators :
 Unary Operators :
64
BipinRupadiya.com
Arithmetic Operators :
OPERATOR MAGIC METHOD
+ __add__(self, other)
– __sub__(self, other)
* __mul__(self, other)
/ __truediv__(self, other)
// __floordiv__(self, other)
% __mod__(self, other)
** __pow__(self, other)
65
BipinRupadiya.com
Comparison Operators :
OPERATOR MAGIC METHOD
< __lt__(self, other)
> __gt__(self, other)
<= __le__(self, other)
>= __ge__(self, other)
== __eq__(self, other)
!= __ne__(self, other)
< __lt__(self, other)
66
BipinRupadiya.com
Assignment Operators :
67
OPERATOR MAGIC METHOD
-= __isub__(self, other)
+= __iadd__(self, other)
*= __imul__(self, other)
/= __idiv__(self, other)
//= __ifloordiv__(self, other)
%= __imod__(self, other)
**= __ipow__(self, other)
BipinRupadiya.com
Unary Operators :
68
OPERATOR MAGIC METHOD
– __neg__(self, other)
+ __pos__(self, other)
~ __invert__(self, other)
BipinRupadiya.com
Method Overloading
 If a method is written in such a way that can perform
more than one task , it is called method overloading.
 Method overloading is not possible in python
 We may overload the methods but can only use the latest
defined method.
 So we can achieve method overloading by writing same
method with several parameters.
 The method perform the operation depending on the number of
argument is passed in the method call.
BipinRupadiya.com
Example-1
70
Output
100
Example-2
Output
11
Hello JVIMS
BipinRupadiya.com
Example-3
Sum of a+b+c : 6
Sum of a+b : 3
Please enter 2 or 3 args
BipinRupadiya.com
Method Overriding
 When there is a method in super class and we write the
same method in the sub class, then sub class method
override the super class method. It is called ‘method
overriding’.
 The programmer overrides the super class methods when he
does not want to use them in sub class .
 Instead he wants a new functionality to the same method in sub
class.
BipinRupadiya.com
Method Overriding
Area of Circle : 314.1592653589793
BipinRupadiya.com
Python
Chapter-15
Abstract Classes and Interfaces
Abstract Method and Abstract Class, Interfaces in Python,
Abstract Classes vs. Interfaces
BipinRupadiya.com
Abstract Method
 An abstract method is a method that is declared, but contains no
implementation.
 Abstract classes may not be instantiated, and require subclasses to
provide implementations for the abstract methods.
 So Abstract is a method whose action is redefined in the sub
classes as per the requirement of the objects.
 Generally abstract methods are written without body since their
body will be defined in the subclass anyhow.
 But it is possible to write an abstract method with body also.
 To mark the method as abstract, we use decorator @abstractmethod.
75
BipinRupadiya.com
Abstract Class
 The way to create the abstract class, is to derive it from a meta class ABC
that belongs to abc(abstract base class) as:
Class Abstractclass(ABC):
 Since all abstract classes should derived from the meta class ABC which
belongs to abc(abstract base class) module, we should import this in
our program.
 A meta class is a class that defines the behaviour of the other classes.
 The meta class ABC defines that the class which is derived from it
becomes an abstract class.
 To import the abc module’ ABC class and abstractmethod decorator we need
to write below code:
from abc import ABC, abstractmethod
or
from abc import *
Class AbstractClassDemo(ABC):
BipinRupadiya.com
Example
BipinRupadiya.com
Example:
 Example to
create an
abstract class
and subclass with
abstract methods
and objects.
Square : 4
Square root : 2.0
Cube : 216
BipinRupadiya.com
Abstract Method and Abstract Class
Lets take another example of car..
 Registration No:
 all car will have same process for it, it will be common for all objects.
 It is an instance variable in car class.
 Fuel Tank:
 All car will have fuel tank and opening and closing of tank will be
same……(Concrete method-openTank())
 Steering:
 Every car will have steering but to operate steering all the methods
are different in every car. …(Abstract method-steering())
 Brakes:
 All car will have breaks but some will have hydraulic breaks , some
have gas break etc…(Abstract method-braking())
BipinRupadiya.com
Example-2
BipinRupadiya.com
fill the fuel in the tank
car regno : 8000
Maruti : manual steering
Maruti : gas breaks
fill the fuel in the tank
car regno : 7000
Santro : power steering
Santro : hydraulic breaks
Example-2
BipinRupadiya.com
Interface In python
 Abstract class contains some abstract method as well as some
concrete method.
 If a class that contains only abstract methods, it becomes
interface.
 None of the method in interface will have body.
 Only method header will be written in the interface.
 As we write only abstract method in the interface, there is
possibility for providing different implementation for those abstract
method as per the object’s requirement.
BipinRupadiya.com
Interface In python
 Since an interface contains methods without body, it is not
possible to create an object of interface.
 In this case, we can create a subclass where all the methods can
be implemented.
 The flexibility lies in the fact that every subclass can provide its
own implementation for the abstract methods of the interface.
 So interface is more powerful compared to class because of
its flexibility of method implementation as per object
requirement.
BipinRupadiya.com
Example
 Suppose we have gone to the shop where only dollars are accepted , we
can not use rupee there
 This money is like class.
 A class satisfies only requirement intended for it.
 It is not useful to handle the other situations.
 Suppose we have international credit card, through which we can pay
dollars, rupee and pounds.
 So here credit cards behave like interface for us.
 As you know credit card is just a plastic card , it does not hold
money, behind the credit card strategy main work is done by our
bank account which is in bank.
 So this bank account can be taken as sub class.
BipinRupadiya.com
Example
BipinRupadiya.com
Example-2
BipinRupadiya.com
Interface Example
OUTPUT
Enter database name : Sybase
connecting Sybase
Disconnecting Sybase
BipinRupadiya.com
Abstract Class Example with same code
OUTPUT
Enter database name : Sybase
connecting Sybase
Disconnecting Sybase
BipinRupadiya.com
Abstract class VS Interface
 Python does not provide the interface concept explicitly.
 It provides abstract classes which can be used as either abstract class or
interfaces.
 So it is up to the programmer when to use abstract classes and when to use
interface.
 An abstract class is a class that is not designed to be instantiated. Abstract
classes can have no implementation, some implementation, or all
implementation. Abstract classes are designed to allow its subclasses share a
common (default) implementation.
 An interface is an empty shell. There are only the signatures of the methods,
which implies that the methods do not have a body. It's just a pattern.
 Python doesn't have (and doesn't need) a formal Interface contract, the Java-
style distinction between abstraction and interface doesn't exist.
BipinRupadiya.com
Bipin S. Rupadiya
(MCA, PGDCA, BCA)
Assistant Professor,
JVIMS-MCA (537), Jamnagar
www.BipinRupadiya.com
90

More Related Content

Similar to Python_Unit_3.pdf

packages and interfaces
packages and interfacespackages and interfaces
packages and interfacesmadhavi patil
 
Java căn bản - Chapter13
Java căn bản - Chapter13Java căn bản - Chapter13
Java căn bản - Chapter13Vince Vo
 
Chapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and PolymorphismChapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and PolymorphismEduardo Bergavera
 
Learn C# Programming - Classes & Inheritance
Learn C# Programming - Classes & InheritanceLearn C# Programming - Classes & Inheritance
Learn C# Programming - Classes & InheritanceEng Teong Cheah
 
Java - Basic Concepts
Java - Basic ConceptsJava - Basic Concepts
Java - Basic ConceptsVicter Paul
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rdConnex
 
Java Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingJava Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingNithyaN19
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesSunil Kumar Gunasekaran
 
PythonOO.pdf oo Object Oriented programming
PythonOO.pdf oo Object Oriented programmingPythonOO.pdf oo Object Oriented programming
PythonOO.pdf oo Object Oriented programmingKhadijaKhadijaAouadi
 
Object Oriented Programming.pptx
Object Oriented Programming.pptxObject Oriented Programming.pptx
Object Oriented Programming.pptxSAICHARANREDDYN
 
Java As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & AppletsJava As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & AppletsHelen SagayaRaj
 
Application package
Application packageApplication package
Application packageJAYAARC
 

Similar to Python_Unit_3.pdf (20)

Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
Java Inheritance
Java InheritanceJava Inheritance
Java Inheritance
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
Java căn bản - Chapter13
Java căn bản - Chapter13Java căn bản - Chapter13
Java căn bản - Chapter13
 
Chapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and PolymorphismChapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and Polymorphism
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
Learn C# Programming - Classes & Inheritance
Learn C# Programming - Classes & InheritanceLearn C# Programming - Classes & Inheritance
Learn C# Programming - Classes & Inheritance
 
Reflection
ReflectionReflection
Reflection
 
Java - Basic Concepts
Java - Basic ConceptsJava - Basic Concepts
Java - Basic Concepts
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rd
 
Hemajava
HemajavaHemajava
Hemajava
 
Java Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingJava Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overriding
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
 
Java basics
Java basicsJava basics
Java basics
 
Java Reflection Concept and Working
Java Reflection Concept and WorkingJava Reflection Concept and Working
Java Reflection Concept and Working
 
PythonOO.pdf oo Object Oriented programming
PythonOO.pdf oo Object Oriented programmingPythonOO.pdf oo Object Oriented programming
PythonOO.pdf oo Object Oriented programming
 
Object Oriented Programming.pptx
Object Oriented Programming.pptxObject Oriented Programming.pptx
Object Oriented Programming.pptx
 
Sonu wiziq
Sonu wiziqSonu wiziq
Sonu wiziq
 
Java As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & AppletsJava As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & Applets
 
Application package
Application packageApplication package
Application package
 

Recently uploaded

Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersChitralekhaTherkar
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 

Recently uploaded (20)

Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of Powders
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 

Python_Unit_3.pdf

  • 2. BipinRupadiya.com GUJARAT TECHNOLOGICAL UNIVERSITY MASTER OF COMPUTER APPLICATIONS (MCA) SEMESTER: III Subject Name: Programming in Python Subject Code : 4639304 2
  • 3. BipinRupadiya.com Unit-3  Classes and Object-oriented Programming:  Chapter-13: Classes:  Chapter-14: Inheritance and Polymorphism:  Chapter-15: Abstract Classes and Interfaces: 3 Text Book: R Nageswara Rao, Core Python Programming, 2nd Edition, Dreamtech Press
  • 4. BipinRupadiya.com Python Chapter-13 Classes Creating a Class, The Self Variable, Constructor, Types of Variables, Namespaces, Types of Methods (Instance Methods, Class Methods, Static Methods), Passing Members of One Class to Another Class, Inner Classes
  • 5. BipinRupadiya.com Class  Class is a model or blueprint to create objects.  We write class with attributes and actions of objects.  Attributes are represented by variables  Actions are performed by methods.  So a class contains methods and variables.  Same methods and variables are also available in objects, as they are created from class.  The variables which are created inside the inside the instance (i.e object) are also called instance variable.
  • 6. BipinRupadiya.com Difference between function and methods  A function inside a class is known as method.  Method is called using two ways.  classname.methodname()  Instancename.methodname()
  • 7. BipinRupadiya.com Class  Syntax : Class Classname(object): attributes def _init_(self): def method1(): def method2():  All classes have a function called __init__(), which is always executed when the class is being initiated.  Use the __init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created.  Here _init_ is the special method to initialize the variable
  • 8. BipinRupadiya.com Class name ,age, marks variables def _init_(self) def talk(self) s1=self
  • 9. BipinRupadiya.com The Self variables  Self is default variable that contains memory address of the instance of the current class.  So we can use self to refer all instance variable and instance methods.  When instance to the class is created, the instance name contains the memory location of the instance.  This memory location is internally passed to self.  We use self in two ways:  def _init_(self)  Here self can be used to refer to the instance variable inside the constructor  def talk(self)  Self can be used as first parameter in the instance method.
  • 10. BipinRupadiya.com Constructor  Constructor is special method that is used to initialize the instance variable of a class.  In a constructor, we create the instance variable and initialize them with some starting values.  For example:  def __init__(self): self.name = “bipin” self.marks = 60  a constructor is called at a time of creating an instance. S1 = Student()  We can write constructor with some parameters too.  def __init__(self, n=‘ ‘ , m=0)  s1 = Student(‘bipin’, 64) //calling
  • 12. BipinRupadiya.com Types of parameter  The variables which are written inside a class are of two types:  Instance Variable  Instance variable are the variables whose separate copy is created in every instance.  Class Variable or Static Variables  In class method contain first parameter default as ‘cls’ with which we can access class variable.  So to access class variable , we need class method with first parameter as ‘cls’.
  • 13. BipinRupadiya.com Example 13 OUTPUT roll no : 1 Name : bipin Mark : 60 roll no : 2 Name : hitesh Mark : 62
  • 14. BipinRupadiya.com Namespace  Namespace represents, a memory block where names are mapped(or linked ) to objects.  For example n=10  Name n is linked to 10 in Namespace.  A class maintains its own namespace called ‘class namespace’.  in the class namespace names are mapped to class variables.  In the instance namespace, the names are mapped to instance variables.
  • 15. BipinRupadiya.com Types of method  The purpose of method is, to process the variable of class in the method.  The variable declared in the class are called class/static variables.  The variable declared in the constructor are called instance variables.  Types of method exist:  Instance method Accessor method Mutator method  Class methods  Static methods
  • 16. BipinRupadiya.com Instance method  This type of methods act upon the instance variable of the class.  Instance method are bound to instance/objects.  Instancename.method()  Since instance variable are available in the instance, instance method need to know the memory address of the instance.  This provided through ‘self’ variable by default as first parameter.  Instance methods are of two types:  Accessor method (getter method-getxxx())  Accessor method simply access or read the data, it does not modify data or variables. def getName(self): return self.name  Mutator method(setter method-setxxx())  Mutator method can also modify the data. def setName(self, name): self.name = name
  • 17. BipinRupadiya.com Class method  These methods act on class levels.  Class methods are the methods which act on class variables or static variables.  These methods are written using @classmethod decorator above them.  By default first parameter for class is cls which refers to class itself.  Format to refer class variable  cls.var  Method calling  Classname.method()
  • 18. BipinRupadiya.com Example 18 OUTPUT Roll No : 1 Name : bipin Mark : 63 Roll No : 2 Name : bipin Mark : 63
  • 19. BipinRupadiya.com Static method  A static method is also a method which is bound to the class and not the object of the class.  A static method can’t access or modify class state  Static method can be use for Example,  setting environmental variables,  counting the numbers of instance of the class or  changing an attribute in another class,  etc, are the task related to class, that handles by the static methods.  Also , static methods can be used to accept some values, process them and return the result.  Static methods are written with decorator @staticmethod above them.
  • 20. BipinRupadiya.com Static method example OUTPUT Roll No : 1 Name : bipin Mark : 63 Roll No : 2 Name : bipin Mark : 63
  • 21. BipinRupadiya.com Class method vs Static Method  A class method takes cls as first parameter while a static method needs no specific parameters.  A class method can access or modify class state while a static method can’t access or modify it.  In general, static methods know nothing about class state. They are utility type methods that take some parameters and work upon those parameters. On the other hand class methods must have class as parameter.  We use @classmethod decorator in python to create a class method and we use @staticmethod decorator to create a static method in python.  When to use what?  We generally use class method to create factory methods. Factory methods return class object ( similar to a constructor ) for different use cases.  We generally use static methods to create utility functions. 21
  • 22. BipinRupadiya.com Passing members of one class to another class  It is possible to pass the members(i.e. attributes and methods) of a class to another class. Roll No : 1 Name : bipin Mark : 60 Roll No : 2 Name : bipin Mark : 63 bipin is Pass
  • 23. BipinRupadiya.com Inner class  Writing a class within another classis known as inner class or nested class.  If we write a class B inside another class A, then B is known as inner class.  If an object is created using a class, the object inside the root class can be used.  A class can have more than one inner classes, but in general inner classes are avoided.
  • 25. BipinRupadiya.com Inner class Name : Mr. abc DOB : 1/2/12
  • 26. BipinRupadiya.com Inner class Name : Mr. abc DOB : 1/2/12
  • 27. BipinRupadiya.com Python Chapter-14 Inheritance and Polymorphism Constructors in Inheritance, Overriding Super Class Constructors and Methods, The super() Method, Types of Inheritance, Single Inheritance, Multiple Inheritance, Method Resolution Order (MRO), Polymorphism, Duck Typing Philosophy of Python, Operator Overloading, Method Overloading, Method Overriding
  • 28. BipinRupadiya.com Basic Inheritance  Code / software re-use is considered one of the golden rules of object-orientated programming.  By using generalization we eliminate duplicated code whenever possible.  One mechanism to achieve this is inheritance  when one subclass can leverage code from another base class.
  • 29. BipinRupadiya.com What Is Inheritance?  Inheritance is when a class uses code constructed within another class. If we think of inheritance in terms of biology, we can think of a child inheriting certain traits from their parent. That is, a child can inherit a parent’s height or eye color. Children also may share the same last name with their parents.  Classes called child classes or subclasses inherit methods and variables from parent classes or base classes.
  • 30. BipinRupadiya.com Basic Inheritance  Technically all classes are a sub-class of a class called Object, so they all inherit from that class.  The class called Object doesn’t really have many attributes or methods, but they give all other classes their structure.  If a class doesn’t explicitly inherit from any other class it implicitly inherits from Object.
  • 31. BipinRupadiya.com Basic Inheritance We can explicitly call the Object class as follows:
  • 32. BipinRupadiya.com Basic Inheritance  A python program to create a Teacher class and store it into teacher.py
  • 33. BipinRupadiya.com Basic Inheritance  Python program to use Teacher class …..name of file is Ch14-P2.py 1 Bipin
  • 34. BipinRupadiya.com Basic Inheritance  Now if we want to use data of Teacher class in other program at that time code Reusability concept comes. Write below code on file 12 Bipin 99
  • 35. BipinRupadiya.com Basic Inheritance  So Inheritance Syntax is given below: class SubClass(BaseClass) class Student(Teacher) //example of it
  • 36. BipinRupadiya.com Constructors in Inheritance  Constructor from super class is inherited in base class.  See below example for that.
  • 37. BipinRupadiya.com Overriding Super Class Constructor and Methods  When the subclass’ constructor is replacing the super class constructor that is called constructor overloading.  When the subclass’ method with same name as super class is replacing the super class method that is called method overloading.
  • 38. BipinRupadiya.com The Super Method  Super is built in method which is used to call the super class constructor or method.  Any constructor written in the super class is not available to the sub class if the sub class has an constructor.  So how can we initialize the super class instance variables and use them in sub class?  Using super()
  • 39. BipinRupadiya.com Types of the Inheritance  Main advantage of inheritance is class reusability.  All classes in python are built from super a single super class called ‘object’.  If a programmer will create his own classes, by default object class will become super class for them internally.  Syntax: class Childclass(Parent class): class Myclass(object):  Types of inheritance, 1. Single Inheritance 2. Multiple Inheritance 3. Multilevel inheritance: 4. Hierarchical inheritance 5. Hybrid inheritance:
  • 40. BipinRupadiya.com Types of the Inheritance 1. Single inheritance: When a child class inherits from only one parent class, it is called as single inheritance. We saw an example above. 2. Multiple inheritance: When a child class inherits from multiple parent classes, it is called as multiple inheritance. Unlike Java and like C++, Python supports multiple inheritance. We specify all parent classes as comma separated list in bracket. 3. Multilevel inheritance: When we have child and grand child relationship. 4. Hierarchical inheritance More than one derived classes are created from a single base. 5. Hybrid inheritance: This form combines more than one form of inheritance. Basically, it is a blend of more than one type of inheritance. 40
  • 42. BipinRupadiya.com Single Inheritance  When a child class inherits from only one parent class, it is called as single inheritance. A B
  • 43. BipinRupadiya.com Multiple inheritance:  When a child class inherits from multiple parent classes, it is called as multiple inheritance. 43 A B C
  • 44. BipinRupadiya.com Problem In Multiple Inheritance c : 30 b : 20 c : 30 a : 10
  • 45. BipinRupadiya.com Problem In Multiple Inheritance  Problem is the Class C is Unable to access construction of both the super classes.  It means C class cant access all the instance variable of both of its super class.  If C class wants to access instance variable of both of its super classes then the solution is to use super().__init__ () in every class. c : 30 a : 10 b : 20
  • 46. BipinRupadiya.com Method Resolution Order(MRO)  In multiple inheritance, any specified attribute or method is searched first in the current class.  If not found, the search continues into parent classes in depth first, in left to right manner without searching the same class twice.  Searching in this way is called Method Resolution order (MRO)  That’s the reason in previous example we get, output like c,a,b.  Three principles followed by MRO: 1. Search the subclass before going for its base classes. 2. When a class is inherited from several classes then it searches in order of left to right in the base class. 3. It will not visit any class more than once. To know about MRO , we can use mro() method as: classname.mro()
  • 47. BipinRupadiya.com Method Resolution Order(MRO)  Use mro() method on class P  Syntax:- print(P.mro()) c : 30 a : 10 b : 20 [<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>]
  • 48. BipinRupadiya.com Multi Level Inheritance 48 A B C When we have child and grand child relationship. It is known as multilevel inheritance c : 30 b : 20 a : 10
  • 49. BipinRupadiya.com Hierarchical inheritance 49 More than one derived classes are created from a single base it is known ad Hierarchical inheritance c : 30 a : 10 ------ b : 20 a : 10 B C A
  • 50. BipinRupadiya.com Hybrid inheritance: 50 This form combines more than one form of inheritance. Basically, it is a blend of more than one type of inheritance. d : 40 b : 20 c : 30 a : 10 B C A D
  • 51. BipinRupadiya.com Polymorphism  It comes from Greek word poly means many and morphism means form.  If something exhibits various forms then it is called polymorphism.  In programming, polymorphism means same function name (but different signatures) being uses for different types.
  • 52. BipinRupadiya.com Polymorphism  In programming, a variable , object or method will also exhibits the same nature as of the sound.  A variable may store a different types of data, object may exhibit different behaviours in different context or method may perform various tasks in python.  This type of behaviour is called polymorphism.  Definition: If a variable, object or method exhibits different behaviour in different context, it is called as polymorphism.
  • 53. BipinRupadiya.com Example of polymorphism 1. Duck typing philosophy of python 2. Operator overloading 3. Method overloading 4. Method overriding
  • 54. BipinRupadiya.com Duck typing philosophy of python  Python variable are name or tags that point to memory location where data is stored.  Python’s type system is strong because every variable and object has type that can be check through type() function.  Python’s type system is dynamic since type of variable is not explicitly is declared. But it changes with the content being stored.  Example  x=10 will take int type  later if you define x=‘hello’ will take str type
  • 55. BipinRupadiya.com Duck typing philosophy of python Python’s duck typing, a special case of dynamic typing, uses techniques characteristic of polymorphism, including late binding and dynamic dispatch”
  • 56. BipinRupadiya.com Duck typing philosophy of python  Similarly , if we want to call a method on an object and we don’t need to check the type of an object , and we don’t want to know weather this method is actually belong to that object or not.  So for this use below code: def call_talk(obj): obj.talk()  The call_talk method is receiving an object ‘obj’ from outside and using this object, it is invoking(or calling) talk() method.  It is not required to mention the type of an object ‘obj’ or to check weather the talk() method belongs to that object or not.
  • 57. BipinRupadiya.com Problem:  If method does not belong to that object , there will be an error called ‘AttributeError”
  • 58. BipinRupadiya.com Duck typing philosophy of python  So, in python we never worry about the type(class) of object .  The object’s type is distinguished only at runtime.  “so, if it walks like a duck and talks like duck ,it must be duck”, this principle we follow. This is called duck typing.
  • 59. BipinRupadiya.com It is not duck typing…! checking the object (or class) type to know weather the method exist in the object or not in this manner it is called as ‘Strong Typing’ but it is not duck typing
  • 60. BipinRupadiya.com Operator Overloading()  We know that operators perform an action for example + perform addition, - perform subtraction …etc  See in below example + is used for addition of integer , concatenation of String and to combine two lists.  So if any operator performs additional operation other than what it is meant for, it is called operator overloading.  example of polymorphism
  • 61. BipinRupadiya.com Operator Overloading  If we use + operator to add two object  It will give error, to do so we need operator overloading  Example
  • 62. BipinRupadiya.com Operator Overloading Example: Use of __add__() method to add the content of objects + operator we can use to add the content of two object so we are giving additional task to the ‘+’ operator to add the content of the object, which come under operator overloading concept. Plus “+” Operator Overload 200
  • 63. BipinRupadiya.com Operator Overloading Grater Than “>” Operator Overload BookY have more pages
  • 64. BipinRupadiya.com Python magic methods or special functions for operator overloading  Arithmetic Operators :  Comparison Operators :  Assignment Operators :  Unary Operators : 64
  • 65. BipinRupadiya.com Arithmetic Operators : OPERATOR MAGIC METHOD + __add__(self, other) – __sub__(self, other) * __mul__(self, other) / __truediv__(self, other) // __floordiv__(self, other) % __mod__(self, other) ** __pow__(self, other) 65
  • 66. BipinRupadiya.com Comparison Operators : OPERATOR MAGIC METHOD < __lt__(self, other) > __gt__(self, other) <= __le__(self, other) >= __ge__(self, other) == __eq__(self, other) != __ne__(self, other) < __lt__(self, other) 66
  • 67. BipinRupadiya.com Assignment Operators : 67 OPERATOR MAGIC METHOD -= __isub__(self, other) += __iadd__(self, other) *= __imul__(self, other) /= __idiv__(self, other) //= __ifloordiv__(self, other) %= __imod__(self, other) **= __ipow__(self, other)
  • 68. BipinRupadiya.com Unary Operators : 68 OPERATOR MAGIC METHOD – __neg__(self, other) + __pos__(self, other) ~ __invert__(self, other)
  • 69. BipinRupadiya.com Method Overloading  If a method is written in such a way that can perform more than one task , it is called method overloading.  Method overloading is not possible in python  We may overload the methods but can only use the latest defined method.  So we can achieve method overloading by writing same method with several parameters.  The method perform the operation depending on the number of argument is passed in the method call.
  • 71. BipinRupadiya.com Example-3 Sum of a+b+c : 6 Sum of a+b : 3 Please enter 2 or 3 args
  • 72. BipinRupadiya.com Method Overriding  When there is a method in super class and we write the same method in the sub class, then sub class method override the super class method. It is called ‘method overriding’.  The programmer overrides the super class methods when he does not want to use them in sub class .  Instead he wants a new functionality to the same method in sub class.
  • 73. BipinRupadiya.com Method Overriding Area of Circle : 314.1592653589793
  • 74. BipinRupadiya.com Python Chapter-15 Abstract Classes and Interfaces Abstract Method and Abstract Class, Interfaces in Python, Abstract Classes vs. Interfaces
  • 75. BipinRupadiya.com Abstract Method  An abstract method is a method that is declared, but contains no implementation.  Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods.  So Abstract is a method whose action is redefined in the sub classes as per the requirement of the objects.  Generally abstract methods are written without body since their body will be defined in the subclass anyhow.  But it is possible to write an abstract method with body also.  To mark the method as abstract, we use decorator @abstractmethod. 75
  • 76. BipinRupadiya.com Abstract Class  The way to create the abstract class, is to derive it from a meta class ABC that belongs to abc(abstract base class) as: Class Abstractclass(ABC):  Since all abstract classes should derived from the meta class ABC which belongs to abc(abstract base class) module, we should import this in our program.  A meta class is a class that defines the behaviour of the other classes.  The meta class ABC defines that the class which is derived from it becomes an abstract class.  To import the abc module’ ABC class and abstractmethod decorator we need to write below code: from abc import ABC, abstractmethod or from abc import * Class AbstractClassDemo(ABC):
  • 78. BipinRupadiya.com Example:  Example to create an abstract class and subclass with abstract methods and objects. Square : 4 Square root : 2.0 Cube : 216
  • 79. BipinRupadiya.com Abstract Method and Abstract Class Lets take another example of car..  Registration No:  all car will have same process for it, it will be common for all objects.  It is an instance variable in car class.  Fuel Tank:  All car will have fuel tank and opening and closing of tank will be same……(Concrete method-openTank())  Steering:  Every car will have steering but to operate steering all the methods are different in every car. …(Abstract method-steering())  Brakes:  All car will have breaks but some will have hydraulic breaks , some have gas break etc…(Abstract method-braking())
  • 81. BipinRupadiya.com fill the fuel in the tank car regno : 8000 Maruti : manual steering Maruti : gas breaks fill the fuel in the tank car regno : 7000 Santro : power steering Santro : hydraulic breaks Example-2
  • 82. BipinRupadiya.com Interface In python  Abstract class contains some abstract method as well as some concrete method.  If a class that contains only abstract methods, it becomes interface.  None of the method in interface will have body.  Only method header will be written in the interface.  As we write only abstract method in the interface, there is possibility for providing different implementation for those abstract method as per the object’s requirement.
  • 83. BipinRupadiya.com Interface In python  Since an interface contains methods without body, it is not possible to create an object of interface.  In this case, we can create a subclass where all the methods can be implemented.  The flexibility lies in the fact that every subclass can provide its own implementation for the abstract methods of the interface.  So interface is more powerful compared to class because of its flexibility of method implementation as per object requirement.
  • 84. BipinRupadiya.com Example  Suppose we have gone to the shop where only dollars are accepted , we can not use rupee there  This money is like class.  A class satisfies only requirement intended for it.  It is not useful to handle the other situations.  Suppose we have international credit card, through which we can pay dollars, rupee and pounds.  So here credit cards behave like interface for us.  As you know credit card is just a plastic card , it does not hold money, behind the credit card strategy main work is done by our bank account which is in bank.  So this bank account can be taken as sub class.
  • 87. BipinRupadiya.com Interface Example OUTPUT Enter database name : Sybase connecting Sybase Disconnecting Sybase
  • 88. BipinRupadiya.com Abstract Class Example with same code OUTPUT Enter database name : Sybase connecting Sybase Disconnecting Sybase
  • 89. BipinRupadiya.com Abstract class VS Interface  Python does not provide the interface concept explicitly.  It provides abstract classes which can be used as either abstract class or interfaces.  So it is up to the programmer when to use abstract classes and when to use interface.  An abstract class is a class that is not designed to be instantiated. Abstract classes can have no implementation, some implementation, or all implementation. Abstract classes are designed to allow its subclasses share a common (default) implementation.  An interface is an empty shell. There are only the signatures of the methods, which implies that the methods do not have a body. It's just a pattern.  Python doesn't have (and doesn't need) a formal Interface contract, the Java- style distinction between abstraction and interface doesn't exist.
  • 90. BipinRupadiya.com Bipin S. Rupadiya (MCA, PGDCA, BCA) Assistant Professor, JVIMS-MCA (537), Jamnagar www.BipinRupadiya.com 90