0% found this document useful (0 votes)
13 views30 pages

Classes and Objects

The document provides an overview of Object-Oriented Programming (OOP) concepts in Python, including classes, objects, methods, inheritance, polymorphism, encapsulation, and data abstraction. It explains the syntax for defining classes and creating objects, as well as the roles of constructors and the different types of inheritance. Additionally, it discusses method overriding and the use of abstract classes in Python.

Uploaded by

manikanta115330
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views30 pages

Classes and Objects

The document provides an overview of Object-Oriented Programming (OOP) concepts in Python, including classes, objects, methods, inheritance, polymorphism, encapsulation, and data abstraction. It explains the syntax for defining classes and creating objects, as well as the roles of constructors and the different types of inheritance. Additionally, it discusses method overriding and the use of abstract classes in Python.

Uploaded by

manikanta115330
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Classes and Objects

Python OOPs Concepts


• Python is also an object-oriented language
• An object-oriented paradigm is to design the program using
classes and objects.
• The object is related to real-word entities such as book, house,
pencil, etc.
• The oops concept focuses on writing the reusable code.
• It is a widespread technique to solve the problem by creating
objects.
Major principles of object-oriented
programming system
• Class
• Object
• Method
• Inheritance
• Polymorphism
• Data Abstraction
• Encapsulation
Python Classes
• De nition of Class Syntax for class declaration:
• A class is considered a
blueprint of objects.
• The class can be def ined as a 1.class ClassName:
collection
logical entityof objects.
that has It is
some a 2. <statement-1>
speci c a ributes and methods. 3. <statement-N>
• For example: if you have an
employee
contain class,
an at then
t
r it
ibute should
and
method, i.e. an
age, salary, etc. email id, name,
Python Objects
• De nition of Object: • Syntax to create an object
• An object is called an
instance of a class. • Objectname= ClassName()
• The object is an entity that
has state and behavior.
• It may be any real-world
object like the mouse,
keyboard, chair, table, pen,
etc.
Python Class
• # de ne a class
and Objects
• class Bike:
• name = ""
• gear = 0
• # create object of class
• bike1 = Bike()
• # access a ributes and assign new values
• bike1.gear = 11
• bike1.name = "Mountain Bike"
• print(f"Name: {bike1.name}, Gears: {bike1.gear} ")
Method
• The method is a function that is associated with an object. In
Python, a method is not unique to class instances. Any object
type can have methods.
Inheritance
• Inheritance is the most important aspect of object-oriented
programming, which simulates the real-world concept of
inheritance. It specif ies that the child object acquires all the
properties and behaviors of the parent object.
• By using inheritance, we can create a class which uses all the
properties and behavior of another class. The new class is
known as a derived class or child class, and the one whose
properties are acquired is known as a base class or parent class.
• It provides the re-usability of the code.
Polymorphism
• Polymorphism contains two words "poly" and "morphs". Poly
means many, and morph means shape. By polymorphism, we
understand that one task can be performed in dif ferent ways.
For example - you have a class animal, and all animals speak.
But they speak dif fe rently. Here, the "speak" behavior is
polymorphic in a sense and depends on the animal. So, the
abstract "animal" concept does not actually "speak", but
specif ic animals (like dogs and cats) have a concrete
implementation of the action "speak".
Encapsulation
• Encapsulation is also an essential aspect of object-oriented
programming. It is used to restrict access to methods and
variables. In encapsulation, code and data are wrapped
together within a single unit from being modi ed by accident.
Data Abstraction
• Data abstraction and encapsulation both are often used as
synonyms. Both are nearly synonyms because data
abstraction is achieved through encapsulation.
• Abstraction is used to hide internal details and show only
functionalities. Abstracting something means to give names to
things so that the name captures the core of what a function
or a whole program does.
• # de ne a class
• class Employee:
• # de ne a property
• employee_id = 0
• # create two objects of the Employee class
• employee1 = Employee()
• employee2 = Employee()
• # access property using employee1
• employee1.employeeID = 1001
• print(f"Employee ID: {employee1.employeeID}")
• # access properties using employee2
• employee2.employeeID = 1002
• print(f"Employee ID: {employee2.employeeID}")
Python Constructors
• A constructor is a special type of method (function) which is
used to initialize the instance members of the class.
• Constructors can be of two types.
1. Parameterized Constructor
2. Non-parameterized Constructor
• Constructor de nition is executed when we create the object of
this class. Constructors also verify that there are enough
resources for the object to perform any start-up task.
Creating the constructor in python
• In Python, the method the __init__() simulates the
constructor of the class. This method is called when the
class is instantiated. It accepts the self-keyword as a f irst
argument which allows accessing the at tributes or method
of the class.
The __init__() Function
__init__() simulates the constructor of class Student:
the class count = 0
Ita isributes.
mostlyEvery
used toclainisstimust
alize the
have claass def __init__(self):
Student.count = Student.count + 1
constructor, even
the default constructor. if it simpl y relie s on s1=Student()
s2=Student()
cldef
ass__ini
Person: s3=Student()
sel f t
.name __(sel
= f,
namename, age): print("The number of students:",Student.count)
self.age = age When we do not include the constructor in the class or
forget to declare it , then that becomes
p1 = Person("John", 36) constructor. It does not perform any task but initializes thethe default
print(p1.name) objects.
print(p1.age) The object of the class will always call the last constructor if
the class has multiple constructors.
Note: The constructor overloading is not allowed in Python.
1. class Employee:
2. def __init__(self, name, id):
3. self.id = id
4. self.name = name
5.
6. def display(self):
7. print("ID: %d \nName: %s" % (self.id, self.name))
8.
9.
10. emp1 = Employee("John", 101)
11. emp2 = Employee("David", 102)
12.
13. # accessing display() method to print employee 1 information
14.
15. emp1.display()
16.
17. # accessing display() method to print employee 2 information
18. emp2.display()
Python Non-Parameterized Constructor
• The non-parameterized constructor uses when we do not want
to manipulate the value or the constructor that has only self as
an argument.
1. class Student:
2. # Constructor - non parameterized
3. def __init__(self):
4. print("This is non parametrized constructor")
5. def show(self,name):
6. print("Hello",name)
7.student = Student()
8. student.show("John")
Python Parameterized Constructor
• The parameterized constructor has multiple parameters along
with the self.
1.class Student:
2. # Constructor - parameterized
3. def __init__(self, name):
4. print("This is parametrized constructor")
5. self.name = name
6. def show(self):
7. print("Hello",self.name)
8. student = Student("John")
9. student.show()
Python Default Constructor
• When we do not include the constructor in the class or forget
todoes
declare it, then that becomes the default constructor.
not perform any task but initializes the objects. It
1.class Student:
2. roll_num = 101
3. name = "Joseph"
4.
5. def display(self):
6. print(self.roll_num,self.name)
7.
8. st = Student()
9. st.display()
Python
class Student:
built-in class functions
def __init__(self, name, id, age): SN Function
self.name = name 1 geta r(obj,name,default)
self.id = id 2 seta r(obj, name,value)
self.age = age
3 dela r(obj, name)
# creates the object of the class Student 4 hasa r(obj, name)
s = Student("John", 101, 22)
# prints the a ribute name of the object s
print(geta r(s, 'name'))
# reset the value of a ribute age to 23
seta r(s, "age", 23)
# prints the modi ed value of age
print(geta r(s, 'age'))
# prints true if the student contains the a ribute with nam
e id
print(hasa r(s, 'id'))
# deletes the a ribute age
Built-in class a ributes SN A ribute Description
It provides the dictionary
1 __dict__ containing the information
about the class namespace.
class Student:
def __init__(self,name,id,age): 2 __doc__ Itthecontains a string which has
class documentation
self.name = name;
self.id = id;
self.age = age 3 __module
__
It is used to access the module
in which, this class is de ned.
def display_details(self):
print("Name:%s, ID:%d, age:
%d"%(self.name,self.id))
s = Student("John",101,22)
print(s.__doc__)
print(s.__dict__)
print(s.__module__)
Python Inheritance
• Being an object-oriented language, Python supports class
inheritance. It allows us to create a new class from an existing
one.
• The newly created class is known as the subclass (child or
derived class).
• The existing class from which the child class inherits is known
as the superclass (parent or base class).
Python Inheritance Syntax
class super_class: # attributes and method definition
# inheritance class sub_class(super_class): # attributes and method of super_class # attributes and method of sub_class

• definea superclass
class super_class:
# attributes and method definition
inheritance
class sub_class(super_class):
# attributes and method of super_class
# attributes and method of sub_class
• class Animal:
# create an object of the subclass
• # a ribute and method of the labrador = Dog()
parent class
• name = "" # access superclass a ribute and method
• labrador.name = "Rohu"
• def eat(self): labrador.eat()
• print("I can eat")
# call subclass method
• # inherit from Animal labrador.display()
• class Dog(Animal):
• # new method in subclass
• def display(self):
• # access name a ribute of
superclass using self
• print("My name is ",
self.name)
• class Animal: #Base class
• def speak(self):
• print("Animal Speaking")
• #The child class Dog inherits the base class Animal
• class Dog(Animal):
• def bark(self):
• print("dog barking")
• #The child class Dogchild inherits another child class Dog
• class DogChild(Dog):
• def eat(self):
• print("Eating bread...")
• d = DogChild()
• d.bark()
Inheritance Types
• There are 5 di erent types of inheritance in Python. They are:
• Single Inheritance: a child class inherits from only one parent
class.
• Multiple Inheritance: a child class inherits from multiple parent
classes.
• Multilevel Inheritance: a child class inherits from its parent
class, which is inheriting from its parent class.
• Hierarchical Inheritance: more than one child class are created
from a single parent class.
• Hybrid Inheritance: combines more than one form of
inheritance.
Advantages of Inheritance
• Code Reusability: Since a child class can inherit all the
functionalities of the parent's class, this allows code reusability.
• E cient Development: Once a functionality is developed, we
can simply inherit it which allows for cleaner code and easy
maintenance.
• Customization: Since we can also add our own functionalities
in the child class, we can inherit only the useful functionalities
and de ne other required features.
Method Overriding
• We can provide some speci c
class Calculation1:
def Summation(self,a,b):
implementation
class method in of
ourthe parent
child class. return a+b;
When
de nedthe
in parent
the class
child method
class with is class Calculation2:
some speci c implementation, def Multiplication(self,a,b):
then the concept is called return a*b;
method overriding. class Derived(Calculation1,Calculation2):
class Animal: def Divide(self,a,b):
def speak(self): return a/b;
print("speaking")
d = Derived()
class Dog(Animal):
def speak(self): print(d.Summation(10,20))
print("Barking") print(d.Multiplication(10,20))
print(d.Divide(10,20))
d = Dog() print(isinstance(d,Derived))
Data abstraction in python
class Employee:
• Abstraction is an important __count = 0;
aspect of object-oriented
programming. def __init__(self):
• In python, we can also Employee.__count = Employee.__count+1
perform data hiding by adding def display(self):
the double underscore (___) as print("The number of employees",Employee.__count
a pre x to the a ribute which
is to be hidden. emp = Employee()
• After this, the a ribute will not try:
be visible outside of the class print(emp.__count)
through the object. nally:
emp.display()
Abstraction classes in Python # Python program to de ne
# abstract class
from abc import ABC
• Abstraction is used to hide the internal functionality of class Polygon(ABC):
the function from the users. User may need to kno # abstract method
w "what function does" but they don't know "how it def sides(self):
does." pass
• A class that consists of one or more abstract method
is called the abstract class. Abstract methods do not class Triangle(Polygon):
contain their implementation. Abstract class can be def sides(self):
inherited by the subclass and abstract method gets its print("Triangle has 3 sides")
de nition in the subclass.
• Python provides the abc (Abstract Base classes) class square(Polygon):
module to use the abstraction in the Python program. def sides(self):
• We use the @abstractmethod decorator to de ne an print("I have 4 sides")
abstract method or if we don't provide the de nition to # Driver code
the method, it automatically becomes the abstract t = Triangle()
method. t.sides()

You might also like