Object-oriented programming (OOP) is a paradigm in programming centered around the concept of "objects." In Python, OOP allows you to create and organize code using classes and objects, enabling you to structure your programs more efficiently, manage complexity, and promote code reusability.The concept of bundling data (attributes) and the methods that work on the data within a single unit (a class). It restricts direct access to some of the object's components and hides the internal state.Focusing on essential features by hiding complex implementation details. It enables working with objects at a higher level of abstraction without worrying about internal complexities.
Python's object-oriented programming provides a powerful way to structure code, promote code reuse, and build more modular and maintainable applications by leveraging these concepts effectively.
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
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’.
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()
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.
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.
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.
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
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
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'>]
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.
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.
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
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
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.
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.
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):
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.
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.