Python OOPs by Divya Anand
Python OOPs by Divya Anand
OOPS overview
Class
A class is collection of objects. A class contains blueprint from which object
are created. It is a logical entity that contains some attributes and methods
Class vs Instance
Classes allow you to create user-defined data structures. Classes define
functions called methods, which identify the behaviors and actions that an
object created from the class can perform with its data.
Python OOPS 1
While the class is the blueprint, an instance is an object that’s built from a
class and contains real data. An instance of the Dog class is not a blueprint
anymore. It’s an actual dog with a name, like Miles, who’s four years old.
On the other hand, class attributes are attributes that have the same value for
all class instances. You can define a class attribute by assigning a value to
a variable name outside of .__init__() .
class Dog:
# class attribute
attr1 = "mammal"
# Instance attribute
def __init__(self, name):
self.name = name
# Driver code
# Object instantiation
Rodger = Dog("Rodger")
Tommy = Dog("Tommy")
# Method II
print("Rodger is a {}".format(Dog.attr1))
print("Tommy is also a {}".format(Dog.attr1))
Python OOPS 2
# Accessing instance attributes
print("My name is {}".format(Rodger.name))
print("My name is {}".format(Tommy.name))
This is important because it allows you to set the initial values of the object's
attributes, which can then be used by the object's methods.
Methods like .__init__() and .__str__() are called dunder methods because they
begin and end with double underscores
Object
An object is an instance of a class. When class is defined, only the description
for the object is defined. So, no memory or storage is allocated.
Method
Methods are functions defined inside the body of a class. They are used to
define the behaviors of an object.
Instance Method
Instance methods are functions that you define inside a class and can only
call on an instance of that class. Just like .__init__() , an instance method always
takes self as its first parameter.
# dog.py
class Dog:
species = "Canis familiaris"
Python OOPS 3
self.name = name
self.age = age
# Instance method
def description(self):
return f"{self.name} is {self.age} years old"
1. .description() returns a string displaying the name and age of the dog.
2. .speak() has one parameter called sound and returns a string containing the
dog’s name and the sound that the dog makes.
Inheritance
Inheritance is the process to derive or inherit the properties from another
class. The class which derives the properties is called child class while the
class from which properties are being derived is called parent class.
Types of Inheritance
Single Inheritance: Single-level inheritance enables a derived class to
inherit characteristics from a single-parent class.
Python OOPS 4
# Python code to demonstrate how parent constructors
# are called.
# parent class
class Person(object):
def display(self):
print(self.name)
print(self.idnumber)
def details(self):
print("My name is {}".format(self.name))
print("IdNumber: {}".format(self.idnumber))
# child class
class Employee(Person):
def __init__(self, name, idnumber, salary, post):
self.salary = salary
self.post = post
def details(self):
print("My name is {}".format(self.name))
print("IdNumber: {}".format(self.idnumber))
print("Post: {}".format(self.post))
Python OOPS 5
# creation of an object variable or an instance
a = Employee('Rahul', 886012, 200000, "Intern")
Polymorphism
Polymorphism means the same function name (but different signatures) being
used for different types. The key difference is the data types and number of
arguments used in function.
Method Overriding
In other words, it is the type of the object being referred to (not the
type of the reference variable) that determines which version of an
overridden method will be executed.
Python OOPS 6
# Python program to demonstrate
# method overriding
# Constructor
def __init__(self):
self.value = "Inside Parent"
# Constructor
def __init__(self):
self.value = "Inside Child"
# Driver's code
obj1 = Parent()
obj2 = Child()
obj1.show()
obj2.show()
Output
Python OOPS 7
Inside Parent
Inside Child
Method Overloading
Two or more methods have the same name but different numbers of
parameters or different types of parameters, or both. These methods
are called overloaded methods and this is called method overloading.
Python does not support method overloading by default. But there are
different ways to achieve method overloading in Python.
Python OOPS 8
# product(4, 5)
Abstraction
Abstraction is used to hide the internal functionality of the function from the
users. The users only interact with the basic implementation of the function,
but inner working is hidden.
Abstract Method
Abstract method of base class force its child class to write the implementation
of the all abstract methods defined in base class. If we do not implement the
abstract methods of base class in the child class then our code will give error.
In the below code method_1 is a abstract method created using
@abstractmethod decorator.
Python OOPS 9
from abc import ABC, abstractmethod
@abstractmethod
def sound(self):
pass
@abstractmethod
def move(self):
pass
def sound(self):
return "Bark"
def move(self):
return "Run"
def sound(self):
return "Chirp"
def move(self):
return "Fly"
Python OOPS 10
dog = Dog()
bird = Bird()
Encapsulation
Encapsulation is also an important 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.
Access Modifier
Protected Member
# Python program to
# demonstrate protected members
# Protected member
self._a = 2 # protected attribute
Python OOPS 11
class Derived(Base):
def __init__(self):
# Calling constructor of
# Base class
Base.__init__(self)
print("Calling protected member of base class: ",
self._a)
obj1 = Derived()
obj2 = Base()
Private Members
Private members are similar to protected members, the difference is that
the class members declared private should neither be accessed outside
the class nor by any base class. In Python, there is no existence
of Private instance variables that cannot be accessed except inside a
class.
However, to define a private member prefix the member name with double
underscore “__”.
Python OOPS 12
# Python program to
# demonstrate private members
class Base:
def __init__(self):
self.a = "GeeksforGeeks" # Public attribute
self.__c = "GeeksforGeeks" # Private attribute
# Calling constructor of
# Base class
Base.__init__(self)
print("Calling private member of base class: ")
print(self.__c) # This will give error since c- is private attribute
# and can't be accessed outside base class
# Driver code
obj1 = Base()
print(obj1.a)
Python OOPS 13
Public Members
Public Attributes can be accessed by any class as well base or child class.
Python OOPS 14