0% found this document useful (0 votes)
22 views15 pages

Python OOP Concepts Explained

The document explains the concepts of Object-Oriented Programming (OOP) in Python, including classes, objects, inheritance, polymorphism, encapsulation, and data abstraction. It details how classes serve as blueprints for creating objects, the significance of the 'self' keyword, and the role of methods such as __init__. The document also covers different types of methods (instance, class, and static), various inheritance types, and the importance of encapsulation in protecting data integrity.

Uploaded by

meetayar2005
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)
22 views15 pages

Python OOP Concepts Explained

The document explains the concepts of Object-Oriented Programming (OOP) in Python, including classes, objects, inheritance, polymorphism, encapsulation, and data abstraction. It details how classes serve as blueprints for creating objects, the significance of the 'self' keyword, and the role of methods such as __init__. The document also covers different types of methods (instance, class, and static), various inheritance types, and the importance of encapsulation in protecting data integrity.

Uploaded by

meetayar2005
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

Python OOPs Concepts

In Python, object-oriented Programming (OOPs) is a programming paradigm


that uses objects and classes in programming. It aims to implement real-
world entities like inheritance, polymorphisms, encapsulation, etc. in the
programming. The main concept of OOPs is to bind the data and the
functions that work on that together as a single unit so that no other part of
the code can access this data.
Main Concepts of Object-Oriented Programming (OOPs)
• Class
• Objects
• Polymorphism
• Encapsulation
• Inheritance
• Data Abstraction

Class
A class is a collection of objects. A class contains the blueprints or the
prototype from which the objects are being created. It is a logical entity that
contains some attributes and methods.
To understand the need for creating a class let’s consider an example, let’s
say you wanted to track the number of dogs that may have different
attributes like breed, age. If a list is used, the first element could be the dog’s
breed while the second element could represent its age. Let’s suppose there
are 100 different dogs, then how would you know which element is supposed
to be which? What if you wanted to add other properties to these dogs? This
lacks organization and it’s the exact need for classes.
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.: [Link]

Class Definition Syntax:


class ClassName:
# Statement-1
.
.
.
# Statement-N

Example: Creating an empty Class in Python

# Python3 program to
# demonstrate defining
# a class
class Dog:
pass

In the above example, we have created a class named dog using the class
keyword.

Objects
The object is an entity that has a state and behavior associated with it. It may
be any real-world object like a mouse, keyboard, chair, table, pen, etc.
Integers, strings, floating-point numbers, even arrays, and dictionaries, are
all objects. More specifically, any single integer or any single string is an
object. The number 12 is an object, the string “Hello, world” is an object, a
list is an object that can hold other objects, and so on. You’ve been using
objects all along and may not even realize it.
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.

Example: Creating an object

obj = Dog()

This will create an object named obj of the class Dog defined above. Before
diving deep into objects and class let us understand some basic keywords
that will we used while working with objects and classes.
The self
1. Class methods must have an extra first parameter in the method
definition. We do not give a value for this parameter when we call
the method, Python provides it
2. If we have a method that takes no arguments, then we still have to
have one argument.
3. This is similar to this pointer in C++ and this reference in Java.
When we call a method of this object as [Link](arg1, arg2), this is
automatically converted by Python into [Link](myobject, arg1,
arg2) – this is all the special self is about.

#it is clearly seen that self and obj is referring to the same object

class check:
def __init__(self):
print("Address of self = ",id(self))

obj = check()
print("Address of class object = ",id(obj))

# this code is Contributed by Samyak Jain

Output
Address of self = 140124194801032
Address of class object = 140124194801032

The __init__ method


The __init__ method is similar to constructors in C++ and Java. It is run as
soon as an object of a class is instantiated. The method is useful to do any
initialization you want to do with your object.

What is __init__ in Python?


The Default __init__ Constructor in C++ and Java. Constructors are used
to initializing the object’s state. The task of constructors is to initialize(assign
values) to the data members of the class when an object of the class is
created. Like methods, a constructor also contains a collection of
statements(i.e. instructions) that are executed at the time of Object creation.
It is run as soon as an object of a class is instantiated. The method is useful
to do any initialization you want to do with your object.

# A Sample class with init method


class Person:

# init method or constructor


def __init__(self, name):
[Link] = name

# Sample Method
def say_hi(self):
print('Hello, my name is', [Link])

p = Person('Nikhil')
p.say_hi()
Output:
Hello, my name is Nikhil

Understanding the code

In the above example, a person name 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.

Below is the example of init in python with parameters


Example of __init__
• Python3
# A Sample class with init method

class Person:

# init method or constructor

def __init__(self, name):

[Link] = name

# Sample Method

def say_hi(self):

print('Hello, my name is', [Link])

# 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
Example 1: Creating a class and object with class and instance
attributes

class Dog:

# class attribute
attr1 = "mammal"

# Instance attribute
def __init__(self, name):
[Link] = name

# Driver code
# Object instantiation
Rodger = Dog("Rodger")
Tommy = Dog("Tommy")

# Accessing class attributes


print("Rodger is a {}".format(Rodger.__class__.attr1))
print("Tommy is also a {}".format(Tommy.__class__.attr1))

# Accessing instance attributes


print("My name is {}".format([Link]))
print("My name is {}".format([Link]))

Output
Rodger is a mammal
Tommy is also a mammal
My name is Rodger
My name is Tommy

Example 2: Creating Class and objects with methods

class Dog:

# class attribute
attr1 = "mammal"

# Instance attribute
def __init__(self, name):
[Link] = name

def speak(self):
print("My name is {}".format([Link]))

# Driver code
# Object instantiation
Rodger = Dog("Rodger")
Tommy = Dog("Tommy")

# Accessing class methods


[Link]()
[Link]()

Output
My name is Rodger
My name is Tommy
In a Python class, we can define three types of methods:

• Instance methods
• Class methods
• Static methods

Instance methods

Instance methods are the most used methods in a Python class. These
methods are only accessible through class objects. If we want to modify any
class variable, this should be done inside an instance method.

The first parameter in these methods is self. self is used to refer to the
current class object’s properties and attributes.

Take a look at the code snippet below to understand this.


class Cricket:
teamName = None

def setTeamName(self, name):


[Link] = name

def getTeamName(self):
return [Link]

c = Cricket()
[Link]('India')
print([Link]())

Output
India

Explanation

• In line 1, we define our class.


• In line 2, we define a class variable and set it to None.
• In lines 4 and 7, we create two instance
methods: setTeamName() and getTeamName().
• In lines 11 and 12, we use the class object to access the instance
methods.

Class methods

Class methods are usually used to access class variables. You can call
these methods directly using the class name instead of creating an object of
that class.

To declare a class method, we need to use the @classmethod decorator. Also,


as in the case of instance methods, self is the keyword used to access the
class variables. In class methods, we use use the cls variable to refer to the
class.
Take a look at the code snippet below to understand this concept.
class Cricket:
teamName = 'India'

@classmethod
def getTeamName(cls):
return [Link]

print([Link]())

Output
India

Explanation

• In line 1, we create our class Cricket.


• In line 2, we define a class variable.
• In line 4, we use the decorator @classmethod to specify the below
method as a class method.
• In line 5, we define our class method. (Note that we have used cls to
access the class variable. You can give any name for this parameter,
but as per the convention, the name of this parameter should be cls.
• In line 8, we call our class method by using the class name instead of
creating an object of the class.

Static methods

Static methods are usually used as a utility function or when we do not


want an inherited class to modify a function definition. These methods do
not have any relation to the class variables and instance variables; so, are
not allowed to modify the class attributes inside a static method.

To declare a static method, we need to use the @staticmethod. Again, we will


be using the cls variable to refer to the class. These methods can be
accessed using the class name as well as class objects.

Take a look at the code snippet below to understand this concept.


class Cricket:
teamName = 'India'

@staticmethod
def utility():
print("This is a static method.")

c1 = Cricket()
[Link]()

[Link]()
Output
This is a static method.
This is a static method.

Explanation

• The code is almost the same, but with a difference in line 4, where
we used the decorator @staticmethod to specify the below method as a
static method.
• Then, in line 9, we call our static method by using the class object
and, in line 11, we call the static method using the class name.

Inheritance
Inheritance is the capability of one class to derive or inherit the properties
from another class. The class that derives properties is called the derived
class or child class and the class from which the properties are being derived
is called the base class or parent class.
Benefits of inheritance are:
• It represents real-world relationships well.
• It provides the reusability of a code. We don’t have to write the
same code again and again. Also, it allows us to add more features
to a class without modifying it.
• It is transitive in nature, which means that if class B inherits from
another class A, then all the subclasses of B would automatically
inherit from class A.
• Inheritance offers a simple, understandable model structure.
• Less development and maintenance expenses result from an
inheritance.
Types of Inheritance –
Single Inheritance:
Single-level inheritance enables a derived class to inherit characteristics
from a single-parent class.
Multilevel Inheritance:
Multi-level inheritance enables a derived class to inherit properties from an
immediate parent class which in turn inherits properties from his parent
class.
Hierarchical Inheritance:
Hierarchical level inheritance enables more than one derived class to inherit
properties from a parent class.
Multiple Inheritance:
Multiple level inheritance enables one derived class to inherit properties from
more than one base class.
# Python code to demonstrate how parent constructors
# are called.

# parent class
class Person(object):

# __init__ is known as the constructor


def __init__(self, name, idnumber):
[Link] = name
[Link] = idnumber

def display(self):
print([Link])
print([Link])

def details(self):
print("My name is {}".format([Link]))
print("IdNumber: {}".format([Link]))

# child class
class Employee(Person):
def __init__(self, name, idnumber, salary, post):
[Link] = salary
[Link] = post

# invoking the __init__ of the parent class


Person.__init__(self, name, idnumber)

def details(self):
print("My name is {}".format([Link]))
print("IdNumber: {}".format([Link]))
print("Post: {}".format([Link]))

# creation of an object variable or an instance


a = Employee('Rahul', 886012, 200000, "Intern")

# calling a function of the class Person using


# its instance
[Link]()
[Link]()

Output
Rahul
886012
My name is Rahul
IdNumber: 886012
Post: Intern
In the above article, we have created two classes i.e. Person (parent class)
and Employee (Child Class). The Employee class inherits from the Person
class. We can use the methods of the person class through employee class
as seen in the display function in the above code. A child class can also
modify the behavior of the parent class as seen through the details() method.
Polymorphism
Polymorphism simply means having many forms. For example, we need to
determine if the given species of birds fly or not, using polymorphism we can
do this using a single function.

class Bird:

def intro(self):
print("There are many types of birds.")

def flight(self):
print("Most of the birds can fly but some cannot.")

class sparrow(Bird):

def flight(self):
print("Sparrows can fly.")

class ostrich(Bird):

def flight(self):
print("Ostriches cannot fly.")

obj_bird = Bird()
obj_spr = sparrow()
obj_ost = ostrich()

obj_bird.intro()
obj_bird.flight()

obj_spr.intro()
obj_spr.flight()

obj_ost.intro()
obj_ost.flight()

Output
There are many types of birds.
Most of the birds can fly but some cannot.
There are many types of birds.
Sparrows can fly.
There are many types of birds.
Ostriches cannot fly.
Encapsulation
Encapsulation is one of the fundamental concepts in object-oriented
programming (OOP). It describes the idea of wrapping data and the methods
that work on data within one unit. This puts restrictions on accessing variables
and methods directly and can prevent the accidental modification of data. To
prevent accidental change, an object’s variable can only be changed by an
object’s method. Those types of variables are known as private variables.
A class is an example of encapsulation as it encapsulates all the data that is
member functions, variables, etc.

# Python program to
# demonstrate private members

# Creating a Base class


class Base:
def __init__(self):
self.a = "GeeksforGeeks"
self.__c = "GeeksforGeeks"

# Creating a derived class


class Derived(Base):
def __init__(self):

# Calling constructor of
# Base class
Base.__init__(self)
print("Calling private member of base class: ")
print(self.__c)

# Driver code
obj1 = Base()
print(obj1.a)

# Uncommenting print(obj1.c) will


# raise an AttributeError

# Uncommenting obj2 = Derived() will


# also raise an AtrributeError as
# private member of base class
# is called inside derived class
Output
GeeksforGeeks
In the above example, we have created the c variable as the private
attribute. We cannot even access this attribute directly and can’t even
change its value.

Data Abstraction

It hides the unnecessary code details from the user. Also, when we do not
want to give out sensitive parts of our code implementation and this is where
data abstraction came.
Data Abstraction in Python can be achieved through creating abstract
classes.

You might also like