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

Python OOPS concepts

Python is an object-oriented programming language that allows the creation and use of classes and objects, focusing on reusable code. Key principles include classes, objects, methods, inheritance, polymorphism, data abstraction, and encapsulation. The document explains the concepts of classes and objects, their attributes and methods, and highlights the differences between object-oriented and procedural programming.

Uploaded by

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

Python OOPS concepts

Python is an object-oriented programming language that allows the creation and use of classes and objects, focusing on reusable code. Key principles include classes, objects, methods, inheritance, polymorphism, data abstraction, and encapsulation. The document explains the concepts of classes and objects, their attributes and methods, and highlights the differences between object-oriented and procedural programming.

Uploaded by

dikshaantil5
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Python OOPs Concepts

Like other general-purpose programming languages, Python is also an object-oriented language


since its beginning.

It allows us to develop applications using an Object-Oriented approach.

In Python, we can easily create and use classes and objects.

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 are given below.

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.

 It is a logical entity that has some specific attributes and methods.

 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.

Some points on Python class:

 Classes are created by keyword class.


 Attributes are the variables that belong to a class.
 Attributes are always public and can be accessed using the dot (.) operator. Eg.:
Myclass.Myattribute

Syntax

class ClassName:
<statement-1>
.
.
<statement-N>

Creating an Empty Class in Python

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.

An object consists of:

 State: It is represented by the attributes of an object. It also reflects the properties of


an object.
 Behavior: It is represented by the methods of an object. It also reflects the response of
an object to other objects.
 Identity: It gives a unique name to an object and enables one object to interact with
other objects.

To understand the state, behavior, and identity, let us take the example of the class dog
(explained above).

 The identity can be considered as the name of the dog.


 State or Attributes can be considered as the breed, age, or color of the dog.
 The behavior can be considered as to whether the dog is eating or sleeping.
Creating an Object

 When an object of a class is created, the class is said to be instantiated.

 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.

 A single class may have any number of instances.

 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:

# Python3 program to demonstrate instantiating a class


class Dog:

# A simple class attribute


attr1 = "mammal"
attr2 = "dog"

# A sample method
def fun(self):
print("I'm a", self.attr1)
print("I'm a", self.attr2)

# Driver code Object instantiation


Rodger = Dog()

# Accessing class attributes and method through objects

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.

 Although it is used to set the object's attributes, it is often referred to as a constructor.

 __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.

 The self-argument is the only one required by the __init__ method.

 This argument refers to the newly generated instance of the class.

 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:

# init method or constructor


def __init__(self, name):
self.name = name

# 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

Understanding the code

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:

# init method or constructor


def __init__(self, name):
self.name = name

# 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

iii. __str__() method


 Python has a particular method called __str__(), that is used to define how a class object
should be represented as a string.
 It is often used to give an object a human-readable textual representation, which is helpful
for logging, debugging, or showing users object information.
 When a class object is used to create a string using the built-in functions print() and str(),
the __str__() function is automatically used.
 You can alter how objects of a class are represented in strings by defining
the __str__() method.

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}."

my_obj = GFG("John", "Microsoft")


print(my_obj)
Output:
My name is John and I work in Microsoft.

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.

iv. Class and Instance Variables


 Instance variables are for data, unique to each instance and
 class variables are for attributes and methods shared by all instances of the class.
 Instance variables are variables whose value is assigned inside a constructor or
method with self,
 whereas class variables are variables whose value is assigned in the class.

 Defining instance variables using a constructor.


# Python3 program to show that the variables with a value assigned in the class
declaration, are class #variables and variables inside methods and constructors are
instance variables.

# Class for Dog


class Dog:
# Class Variable
animal = 'dog'

# The init method or constructor


def __init__(self, breed, color):

# Instance Variable
self.breed = breed
self.color = color

# Objects of Dog class


Rodger = Dog("Pug", "brown")
Buzo = Dog("Bulldog", "black")

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 variables can be accessed using class name also


print("\nAccessing class variable using class name")
print(Dog.animal)
Output:
Rodger details:
Rodger is a dog
Breed: Pug
Color: brown
Buzo details:
Buzo is a dog
Breed: Bulldog
Color: black
Accessing class variable using class name
dog
Explanation:
A class named Dog is defined with a class variable animal set to the string “dog”. Class
variables are shared by all objects of a class and can be accessed using the class name.
Dog class has two instance variables breed and color. Later we are creating two
objects of the Dog class and we are printing the value of both objects with a class
variable named animal.
 Defining instance variables using the normal method:
# Python3 program to show that we can create instance variables inside methods

# Class for Dog

class Dog:

# Class Variable
animal = 'dog'

# The init method or constructor


def __init__(self, breed):
# Instance Variable
self.breed = breed

# Adds an instance variable


def setColor(self, color):
self.color = color

# Retrieves instance variable


def getColor(self):
return self.color

# 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.

v. Modify Object Properties


You can modify properties on objects like this:
Example: Set the age of p1 to 40:
p1.age = 40
- Delete Object Properties

You can delete properties on objects by using the del keyword:

Example: Delete the age property from the p1 object:


del p1.age
- Delete Objects
You can delete objects by using the del keyword:

Example: Delete the p1 object:


del p1

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.
Object-oriented vs. Procedure-oriented Programming languages
The difference between object-oriented and procedure-oriented programming is given below:

Index Object-oriented Programming Procedural Programming

1. Object-oriented programming is Procedural programming uses


the problem-solving approach a list of instructions to do
and used where computation is computation step by step.
done by using objects.

2. It makes the development and In procedural programming, It


maintenance easier. is not easy to maintain the
codes when the project
becomes lengthy.

3. It simulates the real world It doesn't simulate the real


entity. So real-world problems world. It works on step by
can be easily solved through step instructions divided into
oops. small parts called functions.

4. It provides data hiding. So it is Procedural language doesn't


more secure than procedural provide any proper way for
languages. You cannot access data binding, so it is less
private data from anywhere. secure.

5. Example of object-oriented Example of procedural


programming languages is C+ languages are: C, Fortran,
+, Java, .Net, Python, C#, etc. Pascal, VB etc.

You might also like