0% found this document useful (0 votes)
2 views

1.4.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 role of constructors and the different types of inheritance. Additionally, it covers built-in class functions and attributes, method overriding, and the use of abstract classes for data abstraction.

Uploaded by

akhilakrosuri
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

1.4.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 role of constructors and the different types of inheritance. Additionally, it covers built-in class functions and attributes, method overriding, and the use of abstract classes for data abstraction.

Uploaded by

akhilakrosuri
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, 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
• Definition of Class Syntax for class
• A class is considered a blueprint declaration:
of objects.
• The class can be defined as a
collection of objects. It is a 1.class ClassName:
logical entity that has some
specific attributes and methods. 2. <statement-
• For example: if you have an
1>
employee class, then it should 3. <statement-N>
contain an attribute and
method, i.e. an email id, name,
age, salary, etc.
Python Objects

• Definition of Object: • Syntax to create an object

• An object is called an
instance of a class.
• Objectname=
• The object is an entity that
has state and behavior. ClassName()
• It may be any real-world
object like the mouse,
keyboard, chair, table, pen,
etc.
Python Class and Objects
• # define a class
• class Bike:
• name = ""
• gear = 0

• # create object of class


• bike1 = Bike()

• # access attributes 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 specifies 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 different ways. For example - you have a
class animal, and all animals speak. But they speak
differently. Here, the "speak" behavior is polymorphic in
a sense and depends on the animal. So, the abstract
"animal" concept does not actually "speak", but specific
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
modified 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.
• # define a class
• class Employee:
• # define 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
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 definition 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 first argument which allows accessing the
attributes or method of the class.
The __init__() Function
__init__() simulates the constructor of the class class Student:
It is mostly used to initialize the class attributes. count = 0
Every class must have a constructor, even if it def __init__(self):
Student.count = Student.count + 1
simply relies on the default constructor.
s1=Student()
class Person: s2=Student()
def __init__(self, name, age): s3=Student()
self.name = name print("The number of students:",Student.count)
self.age = age
When we do not include the constructor in the class or forget to
p1 = Person("John", 36) declare it, then that becomes the default constructor. It does not
perform any task but initializes the objects.
print(p1.name)
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
to declare it, then that becomes the default constructor. It
does not perform any task but initializes the objects.
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 built-in class functions
class Student:
def __init__(self, name, id, age): SN Function
self.name = name
1 getattr(obj,name,default)
self.id = id
2 setattr(obj, name,value)
self.age = age
3 delattr(obj, name)
# creates the object of the class Student 4 hasattr(obj, name)
s = Student("John", 101, 22)
# prints the attribute name of the object s
print(getattr(s, 'name'))
# reset the value of attribute age to 23
setattr(s, "age", 23)
# prints the modified value of age
print(getattr(s, 'age'))
# prints true if the student contains the attribute with name id
print(hasattr(s, 'id'))
# deletes the attribute age
delattr(s, 'age')
# this will give an error since the attribute age has been deleted
print(s.age)
Built-in class attributes SN Attribute Description

It provides the dictionary containing


1 __dict__ the information about the class
namespace.

class Student: It contains a string which has the


def __init__(self,name,id,age): 2 __doc__
class documentation
self.name = name;
self.id = id;
__module_ It is used to access the module in
self.age = age 3
_ which, this class is defined.
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).
ss super_class: # attributes and method definition
# inheritance class sub_class(super_class): # attributes and method of super_class # attributes and method of sub_class

Python Inheritance Syntax

• define a 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
labrador = Dog()
• # attribute and method of the
parent class # access superclass attribute and method
• name = "" labrador.name = "Rohu"
• labrador.eat()
• def eat(self): # call subclass method
• print("I can eat") labrador.display()

• # inherit from Animal


• class Dog(Animal):

• # new method in subclass


• def display(self):
• # access name attribute 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()
• d.speak()
Inheritance Types
• There are 5 different 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
Advantages of Inheritance
• Code Reusability: Since a child class can inherit all the
functionalities of the parent's class, this allows code
reusability.
• Efficient 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 define other required features.
Method Overriding
class Calculation1:
• We can provide some specific def Summation(self,a,b):
return a+b;
implementation of the parent class
method in our child class. When the class Calculation2:
parent class method is defined in the def Multiplication(self,a,b):
child class with some specific return a*b;
implementation, then the concept is
called method overriding. class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
class Animal:
return a/b;
def speak(self):
print("speaking")
d = Derived()
class Dog(Animal):
print(d.Summation(10,20))
def speak(self):
print(d.Multiplication(10,20))
print("Barking")
print(d.Divide(10,20))
print(isinstance(d,Derived))
d = Dog()
d.speak()
Data abstraction in python
class Employee:
• Abstraction is an important __count = 0;
aspect of object-oriented
programming. def __init__(self):
Employee.__count = Employee.__count+1
• In python, we can also perform
data hiding by adding the double def display(self):
underscore (___) as a prefix to print("The number of employees",Employee.__count)
the attribute which is to be
emp = Employee()
hidden. try:
• After this, the attribute will not print(emp.__count)
finally:
be visible outside of the class emp.display()
through the object.
# Python program to define
Abstraction classes in Python # abstract class
from abc import ABC

• Abstraction is used to hide the internal functionality of the class Polygon(ABC):


function from the users. User may need to know "what # abstract method
function does" but they don't know "how it does." def sides(self):
• A class that consists of one or more abstract method is called pass
the abstract class. Abstract methods do not contain their
class Triangle(Polygon):
implementation. Abstract class can be inherited by the
def sides(self):
subclass and abstract method gets its definition in the
print("Triangle has 3 sides")
subclass.
• Python provides the abc (Abstract Base classes) module to class square(Polygon):
use the abstraction in the Python program. def sides(self):
• We use the @abstractmethod decorator to define an print("I have 4 sides")
abstract method or if we don't provide the definition to the
method, it automatically becomes the abstract method. # Driver code
t = Triangle()
t.sides()

s = square()
s.sides()

You might also like