Python OOPS concepts
Python OOPS concepts
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.
o Class
o Object
o Method
o Inheritance
o Polymorphism
o Data Abstraction
o Encapsulation
Python Class
The class can be defined as a collection of objects.
For example: if you have an employee class, then it should contain an attribute and
method, i.e. an email id, name, age, salary, etc.
Syntax
class ClassName:
<statement-1>
.
.
<statement-N>
In the above example, we have created a class named Dog using the class keyword.
class Dog:
pass
Python Object
The object is an entity that has state, behavior and Identity.
It may be any real-world object like the mouse, keyboard, chair, table, pen, etc.
Everything in Python is an object, and almost everything has attributes and methods.
All functions have a built-in attribute __doc__, which returns the docstring defined in the
function source code.
To understand the state, behavior, and identity, let us take the example of the class dog
(explained above).
All the instances share the attributes and the behavior of the class.
But the values of those attributes, i.e. the state are unique for each object.
This will create an object named obj of the class Dog defined above.
obj = Dog()
When we define a class, it needs to create an object to allocate the memory. Consider the
following examples.
Example 1:
# A sample method
def fun(self):
print("I'm a", self.attr1)
print("I'm a", self.attr2)
print(Rodger.attr1)
Rodger.fun()
Output:
mammal
I'm a mammal
I'm a dog
In the above example, an object is created which is basically a dog named Rodger. This
class only has two class attributes that tell us that Rodger is a dog and a mammal.
Example 2:
class car:
def __init__(self,modelname, year):
self.modelname = modelname
self.year = year
def display(self):
print(self.modelname,self.year)
c1 = car("Toyota", 2016)
c1.display()
Output:
Toyota 2016
In the above example, we have created the class named car, and it has two attributes
modelname and year. We have created a c1 object to access the class attribute. The c1
object will allocate memory for these values.
Before diving deep into objects and classes let us understand some basic keywords that will be
used while working with objects and classes.
i. The self-parameter
The self-parameter refers to the current instance of the class and accesses the class
variables. We can use anything instead of self, but it must be the first parameter of any
function which belongs to the class.
Whenever you call a method of an object created from a class, the object is
automatically passed as the first argument using the “self” parameter.
This enables you to modify the object’s properties and execute tasks unique to that
particular instance.
class mynumber:
def __init__(self, value):
self.value = value
def print_value(self):
print(self.value)
obj1 = mynumber(17)
obj1.print_value()
Output:
17
ii. _ _init_ _ method
In order to make an instance of a class in Python, a specific function called __init__ is
called.
__init__ method is like default constructor in C++ and Java. The task of constructors is
to initialize(assign values) to the data members of the class when an object of the class
is created.
Additionally, to initialize the values of each attribute associated with the objects, you
can declare extra arguments in the __init__ method.
The method is useful to do any initialization you want to do with your object.
Example 1:
# A Sample class with init method
class Person:
# Sample Method
def say_hi(self):
print('Hello, my name is', self.name)
p = Person('Nikhil')
p.say_hi()
Output:
Hello, my name is Nikhil
In the above example, a person named Nikhil is created. While creating a person,
“Nikhil” is passed as an argument, this argument will be passed to the __init__ method
to initialize the object.
The keyword self represents the instance of a class and binds the attributes with the
given arguments. Similarly, many objects of the Person class can be created by passing
different names as arguments.
Example 2:
# A Sample class with init method
class Person:
# Sample Method
def say_hi(self):
print('Hello, my name is', self.name)
# Creating different objects
p1 = Person('Nikhil')
p2 = Person('Abhinav')
p3 = Person('Anshul')
p1.say_hi()
p2.say_hi()
p3.say_hi()
Output:
Hello, my name is Nikhil
Hello, my name is Abhinav
Hello, my name is Anshul
class GFG:
def __init__(self, name, company):
self.name = name
self.company = company
def __str__(self):
return f"My name is {self.name} and I work in {self.company}."
Explanation:
In this example, We are creating a class named GFG.In the class, we are creating two
instance variables name and company. In the __str__() method we are returning
the name instance variable and company instance variable. Finally, we are creating the
object of GFG class and we are calling the __str__() method.
# Instance Variable
self.breed = breed
self.color = color
print('Rodger details:')
print('Rodger is a', Rodger.animal)
print('Breed: ', Rodger.breed)
print('Color: ', Rodger.color)
print('\nBuzo details:')
print('Buzo is a', Buzo.animal)
print('Breed: ', Buzo.breed)
print('Color: ', Buzo.color)
class Dog:
# Class Variable
animal = 'dog'
# Driver Code
Rodger = Dog("pug")
Rodger.setColor("brown")
print(Rodger.getColor())
Output:
brown
Explanation:
In this example, We have defined a class named Dog and we have created a class
variable animal. We have created an instance variable breed in the constructor. The
class Dog consists of two methods setColor and getColor, they are used for creating
and initializing an instance variable and retrieving the value of the instance variable. We
have made an object of the Dog class and we have set the instance variable value to
brown and we are printing the value in the terminal.
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.
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.
Object-oriented vs. Procedure-oriented Programming languages
The difference between object-oriented and procedure-oriented programming is given below: