[go: up one dir, main page]

0% found this document useful (0 votes)
3 views14 pages

Python OOPs by Divya Anand

The document provides an overview of Object-Oriented Programming (OOP) in Python, covering key concepts such as classes, instances, attributes, methods, inheritance, polymorphism, abstraction, and encapsulation. It explains the differences between class and instance attributes, the role of the init method, and various types of inheritance. Additionally, it discusses method overriding, method overloading, and access modifiers for encapsulation.

Uploaded by

leggasickvincent
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)
3 views14 pages

Python OOPs by Divya Anand

The document provides an overview of Object-Oriented Programming (OOP) in Python, covering key concepts such as classes, instances, attributes, methods, inheritance, polymorphism, abstraction, and encapsulation. It explains the differences between class and instance attributes, the role of the init method, and various types of inheritance. Additionally, it discusses method overriding, method overloading, and access modifiers for encapsulation.

Uploaded by

leggasickvincent
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
You are on page 1/ 14

Python OOPS

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.

Class Attributes vs Instance Attributes


Attributes created in .__init__() are called instance attributes. An instance
attribute’s value is specific to a particular instance of the class. All Dog objects
have a name and an age, but the values for the name and age attributes will
vary depending on the Dog instance.

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")

# Accessing class attributes


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

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

The Python Init Method


The init method is a special method in Python classes that is called when an
object is created.
It is used to initialize the object's attributes.

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"

def __init__(self, name, age):

Python OOPS 3
self.name = name
self.age = age

# Instance method
def description(self):
return f"{self.name} is {self.age} years old"

# Another instance method


def speak(self, sound):
return f"{self.name} says {sound}"

This Dog class has two instance methods:

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.

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 OOPS 4
# 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):
self.name = name
self.idnumber = idnumber

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

# invoking the __init__ of the parent class


# Method I
Person.__init__(self, name, idnumber)
# Method II
super().__init__(name,idnumber)

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")

# calling a function of the class Person using


# its instance
a.display()
a.details()

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

Method overriding is an ability of any object-oriented programming


language that allows a subclass or child class to provide a specific
implementation of a method that is already provided by one of its
super-classes or parent classes.

When a method in a subclass has the same name, same parameters or


signature and same return type(or sub-type) as a method in its super-
class, then the method in the subclass is said to override the method in
the super-class.

The version of a method that is executed will be determined by the


object that is used to invoke it. If an object of a parent class is used to
invoke the method, then the version in the parent class will be
executed, but if an object of the subclass is used to invoke the method,
then the version in the child class will be executed.

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

# Defining parent class


class Parent():

# Constructor
def __init__(self):
self.value = "Inside Parent"

# Parent's show method


def show(self):
print(self.value)

# Defining child class


class Child(Parent):

# Constructor
def __init__(self):
self.value = "Inside Child"

# Child's show method


def show(self):
print(self.value)

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

The problem with method overloading in Python is that we may


overload the methods but can only use the latest defined method.

# First product method.


# Takes two argument and print their
# product

def product(a, b):


p=a*b
print(p)

# Second product method


# Takes three argument and print their
# product

def product(a, b, c):


p = a * b*c
print(p)

# Uncommenting the below line shows an error

Python OOPS 8
# product(4, 5)

# This line will call the second product method


product(4, 5, 5)

# In the above code, we have defined two product methods


# we can only use the second product method,
# as python does not support method overloading.
# We may define many methods of the same name and different argumen
# but we can only use the latest defined method.
# Calling the other method will produce an error.
# Like here calling product(4,5) will produce an error
# as the latest defined product method takes three arguments.

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.

In Python, abstract method feature is not a default feature. To create abstract


method and abstract classes we have to import the “ABC” and
“abstractmethod” classes from abc (Abstract Base Class) library.

Abstraction classes in Python


Abstract class is a class in which one or more abstract methods are
defined. When a method is declared inside the class without its
implementation is known as abstract method.

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

# Defining an abstract base class


class Animal(ABC):

@abstractmethod
def sound(self):
pass

@abstractmethod
def move(self):
pass

# Defining a subclass that implements the abstract methods


class Dog(Animal):

def sound(self):
return "Bark"

def move(self):
return "Run"

# Defining another subclass that implements the abstract methods


class Bird(Animal):

def sound(self):
return "Chirp"

def move(self):
return "Fly"

# Trying to instantiate the abstract class will raise an error


# animal = Animal() # This will raise a TypeError

# Instantiating the subclasses

Python OOPS 10
dog = Dog()
bird = Bird()

# Using the implemented methods


print(dog.sound()) # Output: Bark
print(dog.move()) # Output: Run
print(bird.sound()) # Output: Chirp
print(bird.move()) # Output: Fly

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

Protected members are those members of the class that cannot be


accessed outside the class but can be accessed from within the class and
its subclasses. To accomplish this in Python, just follow the convention by
prefixing the name of the member by a single underscore “_”.

# Python program to
# demonstrate protected members

# Creating a base class


class Base:
def __init__(self):

# Protected member
self._a = 2 # protected attribute

# Creating a derived class

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)

# Modify the protected variable:


self._a = 3
print("Calling modified protected member outside class: ",
self._a)

obj1 = Derived()

obj2 = Base()

# Calling protected member


# Can be accessed but should not be done due to convention
print("Accessing protected member of obj1: ", obj1._a)

# Accessing the protected variable outside


print("Accessing protected member of obj2: ", obj2._a)

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

# Creating a Base class

class Base:
def __init__(self):
self.a = "GeeksforGeeks" # Public attribute
self.__c = "GeeksforGeeks" # Private attribute

# 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) # This will give error since c- is private attribute
# and can't be accessed outside base class

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

# Uncommenting print(obj1.c) will


# raise an AttributeError

# Uncommenting obj2 = Derived() will


# also raise an AttributeError as
# private member of base class
# is called inside derived class

Python OOPS 13
Public Members
Public Attributes can be accessed by any class as well base or child class.

Python OOPS 14

You might also like