Python supports object-oriented programming through classes, objects, and related concepts like inheritance, polymorphism, and encapsulation. A class acts as a blueprint to create object instances. Objects contain data fields and methods. Inheritance allows classes to inherit attributes and behaviors from parent classes. Polymorphism enables the same interface to work with objects of different types. Encapsulation helps protect data by restricting access.
Object in python tells about object oriented programming in pythonReshmiShaw2
This document presents an overview of objects in Python. It defines what objects and classes are, explaining that objects are instances of classes that combine data and methods. It provides examples of defining a class called Person with name and age attributes and a greet method. It then instantiates Person objects called person1 and person2, demonstrating how they have unique attribute values but share the class's methods. The document concludes by acknowledging the Python community and citing references used.
Object-oriented programming (OOP) organizes code around data objects rather than functions. In Python, classes are user-defined templates for objects that contain attributes (data) and methods (functions). When a class is instantiated, an object is created with its own copies of the attributes. Self refers to the object itself and allows methods to access and modify its attributes. Classes in Python allow for code reusability, modularity, and flexibility through encapsulation, inheritance, and polymorphism.
Here is a Python class with the specifications provided in the question:
class PICTURE:
def __init__(self, pno, category, location):
self.pno = pno
self.category = category
self.location = location
def FixLocation(self, new_location):
self.location = new_location
This defines a PICTURE class with three instance attributes - pno, category and location as specified in the question. It also defines a FixLocation method to assign a new location as required.
Python Programming - VI. Classes and ObjectsRanel Padon
This document discusses classes and objects in Python programming. It covers key concepts like class attributes, instantiating classes to create objects, using constructors and destructors, composition where objects have other objects as attributes, and referencing objects. The document uses examples like a Time class to demonstrate class syntax and how to define attributes and behaviors for classes.
Anton Kasyanov, Introduction to Python, Lecture5Anton Kasyanov
Classes allow users to create custom types in Python. A class defines the form and behavior of a custom type using methods. Objects or instances are created from a class and can have their own state and values. Common class methods include __init__() for initializing objects and setting initial values, and other methods like set_age() for modifying object attributes. Classes can inherit behaviors from superclasses and override existing methods.
Python allows importing and using classes and functions defined in other files through modules. There are three main ways to import modules: import somefile imports everything and requires prefixing names with the module name, from somefile import * imports everything without prefixes, and from somefile import className imports a specific class. Modules look for files in directories listed in sys.path.
Classes define custom data types by storing shared data and methods. Instances are created using class() and initialized with __init__. Self refers to the instance inside methods. Attributes store an instance's data while class attributes are shared. Inheritance allows subclasses to extend and redefine parent class features. Special built-in methods control class behaviors like string representation or iteration.
The document discusses Python programming concepts including lists, dictionaries, tuples, regular expressions, classes, objects, and methods. Key points:
- Lists are mutable sequences that can contain elements of any type. Dictionaries store elements as key-value pairs. Tuples are immutable sequences.
- Classes create user-defined data types by binding data (attributes) and functionality (methods). Objects are instances of classes that consume memory at runtime.
- Common methods include __init__() for initializing attributes and __str__() for string representation of objects. Computation is expressed through operations on objects, often representing real-world things.
This document discusses object-oriented programming concepts in Python including classes, objects, attributes, methods, inheritance, polymorphism, and special methods. Key points include:
- Classes are templates that define objects, while objects are instantiations of classes with unique attribute values.
- Methods define object behaviors. The self parameter refers to the current object instance.
- Inheritance allows classes to extend existing classes, reusing attributes and methods from parent classes.
- Special methods with double underscores have predefined meanings (e.g. __init__ for constructors, __repr__ for string representation).
The document discusses Python objects and types. It covers key concepts like object-oriented programming in Python, classes and instances, namespaces, scoping, and exception handling. Some main points include:
- Everything in Python is an object with an identity, type, and value. Objects live in dynamic namespaces and can be accessed via names.
- Classes are type objects that act as templates for creating instances when called. Instances are objects with the same methods and attributes as its class.
- Namespaces are where names are mapped to objects. Python has module, class, and instance namespaces that follow LEGB scoping rules.
- Exceptions are class objects that inherit from the built-in Exception class. The raise statement is used
Chap 3 Python Object Oriented Programming - Copy.pptmuneshwarbisen1
The document discusses object oriented programming concepts in Python including classes, objects, instances, methods, inheritance, and class attributes. It provides examples of defining classes, instantiating objects, using methods, and the difference between class and instance attributes. Key concepts covered include defining classes with the class keyword, creating object instances, using the __init__() method for initialization, and allowing derived classes to inherit from base classes.
This document discusses object-oriented programming concepts in Python including:
- Classes define templates for objects with attributes and methods. Objects are instances of classes.
- The __init__ method initializes attributes when an object is constructed.
- Classes can make attributes private using double underscores. Encapsulation hides implementation details.
- Objects can be mutable, allowing state changes, or immutable like strings which cannot change.
- Inheritance allows subclasses to extend and modify parent class behavior through polymorphism.
The document outlines an advanced Python course covering various Python concepts like object orientation, comprehensions, extended arguments, closures, decorators, generators, context managers, classmethods, inheritance, encapsulation, operator overloading, and Python packages. The course agenda includes how everything in Python is an object, comprehension syntax, *args and **kwargs, closures and decorators, generators and iterators, context managers, staticmethods and classmethods, inheritance and encapsulation, operator overloading, and Python package layout.
This document provides an overview of object-oriented programming concepts in Python including objects, classes, inheritance, polymorphism, and encapsulation. It defines key terms like objects, classes, and methods. It explains how to create classes and objects in Python. It also discusses special methods, modules, and the __name__ variable.
در این جلسه به بررسی بحث برنامه نویسی شی گرا و کلاس ها در پایتون پرداختیم
PySec101 Fall 2013 J7E1 By Mohammad Reza Kamalifard
Talk About:
Object oriented programming and Classes in Python
The document introduces Python modules and importing. It discusses three formats for importing modules: import somefile, from somefile import *, and from somefile import className. It describes commonly used Python modules like sys, os, and math. It also covers defining your own modules, directories for module files, object-oriented programming in Python including defining classes, creating and deleting instances, methods and self, accessing attributes and methods, attributes, inheritance, and redefining methods.
Python programming computer science and engineeringIRAH34
Python supports object-oriented programming (OOP) through classes and objects. A class defines the attributes and behaviors of an object, while an object is an instance of a class. Inheritance allows classes to inherit attributes and methods from parent classes. Polymorphism enables classes to define common methods that can behave differently depending on the type of object. Operator overloading allows classes to define how operators like + work on class objects.
Rearchitecturing a 9-year-old legacy Laravel application.pdfTakumi Amitani
An initiative to re-architect a Laravel legacy application that had been running for 9 years using the following approaches, with the goal of improving the system’s modifiability:
・Event Storming
・Use Case Driven Object Modeling
・Domain Driven Design
・Modular Monolith
・Clean Architecture
This slide was used in PHPxTKY June 2025.
https://phpxtky.connpass.com/event/352685/
More Related Content
Similar to UNIT-5 object oriented programming lecture (20)
Anton Kasyanov, Introduction to Python, Lecture5Anton Kasyanov
Classes allow users to create custom types in Python. A class defines the form and behavior of a custom type using methods. Objects or instances are created from a class and can have their own state and values. Common class methods include __init__() for initializing objects and setting initial values, and other methods like set_age() for modifying object attributes. Classes can inherit behaviors from superclasses and override existing methods.
Python allows importing and using classes and functions defined in other files through modules. There are three main ways to import modules: import somefile imports everything and requires prefixing names with the module name, from somefile import * imports everything without prefixes, and from somefile import className imports a specific class. Modules look for files in directories listed in sys.path.
Classes define custom data types by storing shared data and methods. Instances are created using class() and initialized with __init__. Self refers to the instance inside methods. Attributes store an instance's data while class attributes are shared. Inheritance allows subclasses to extend and redefine parent class features. Special built-in methods control class behaviors like string representation or iteration.
The document discusses Python programming concepts including lists, dictionaries, tuples, regular expressions, classes, objects, and methods. Key points:
- Lists are mutable sequences that can contain elements of any type. Dictionaries store elements as key-value pairs. Tuples are immutable sequences.
- Classes create user-defined data types by binding data (attributes) and functionality (methods). Objects are instances of classes that consume memory at runtime.
- Common methods include __init__() for initializing attributes and __str__() for string representation of objects. Computation is expressed through operations on objects, often representing real-world things.
This document discusses object-oriented programming concepts in Python including classes, objects, attributes, methods, inheritance, polymorphism, and special methods. Key points include:
- Classes are templates that define objects, while objects are instantiations of classes with unique attribute values.
- Methods define object behaviors. The self parameter refers to the current object instance.
- Inheritance allows classes to extend existing classes, reusing attributes and methods from parent classes.
- Special methods with double underscores have predefined meanings (e.g. __init__ for constructors, __repr__ for string representation).
The document discusses Python objects and types. It covers key concepts like object-oriented programming in Python, classes and instances, namespaces, scoping, and exception handling. Some main points include:
- Everything in Python is an object with an identity, type, and value. Objects live in dynamic namespaces and can be accessed via names.
- Classes are type objects that act as templates for creating instances when called. Instances are objects with the same methods and attributes as its class.
- Namespaces are where names are mapped to objects. Python has module, class, and instance namespaces that follow LEGB scoping rules.
- Exceptions are class objects that inherit from the built-in Exception class. The raise statement is used
Chap 3 Python Object Oriented Programming - Copy.pptmuneshwarbisen1
The document discusses object oriented programming concepts in Python including classes, objects, instances, methods, inheritance, and class attributes. It provides examples of defining classes, instantiating objects, using methods, and the difference between class and instance attributes. Key concepts covered include defining classes with the class keyword, creating object instances, using the __init__() method for initialization, and allowing derived classes to inherit from base classes.
This document discusses object-oriented programming concepts in Python including:
- Classes define templates for objects with attributes and methods. Objects are instances of classes.
- The __init__ method initializes attributes when an object is constructed.
- Classes can make attributes private using double underscores. Encapsulation hides implementation details.
- Objects can be mutable, allowing state changes, or immutable like strings which cannot change.
- Inheritance allows subclasses to extend and modify parent class behavior through polymorphism.
The document outlines an advanced Python course covering various Python concepts like object orientation, comprehensions, extended arguments, closures, decorators, generators, context managers, classmethods, inheritance, encapsulation, operator overloading, and Python packages. The course agenda includes how everything in Python is an object, comprehension syntax, *args and **kwargs, closures and decorators, generators and iterators, context managers, staticmethods and classmethods, inheritance and encapsulation, operator overloading, and Python package layout.
This document provides an overview of object-oriented programming concepts in Python including objects, classes, inheritance, polymorphism, and encapsulation. It defines key terms like objects, classes, and methods. It explains how to create classes and objects in Python. It also discusses special methods, modules, and the __name__ variable.
در این جلسه به بررسی بحث برنامه نویسی شی گرا و کلاس ها در پایتون پرداختیم
PySec101 Fall 2013 J7E1 By Mohammad Reza Kamalifard
Talk About:
Object oriented programming and Classes in Python
The document introduces Python modules and importing. It discusses three formats for importing modules: import somefile, from somefile import *, and from somefile import className. It describes commonly used Python modules like sys, os, and math. It also covers defining your own modules, directories for module files, object-oriented programming in Python including defining classes, creating and deleting instances, methods and self, accessing attributes and methods, attributes, inheritance, and redefining methods.
Python programming computer science and engineeringIRAH34
Python supports object-oriented programming (OOP) through classes and objects. A class defines the attributes and behaviors of an object, while an object is an instance of a class. Inheritance allows classes to inherit attributes and methods from parent classes. Polymorphism enables classes to define common methods that can behave differently depending on the type of object. Operator overloading allows classes to define how operators like + work on class objects.
Rearchitecturing a 9-year-old legacy Laravel application.pdfTakumi Amitani
An initiative to re-architect a Laravel legacy application that had been running for 9 years using the following approaches, with the goal of improving the system’s modifiability:
・Event Storming
・Use Case Driven Object Modeling
・Domain Driven Design
・Modular Monolith
・Clean Architecture
This slide was used in PHPxTKY June 2025.
https://phpxtky.connpass.com/event/352685/
PREDICTION OF ROOM TEMPERATURE SIDEEFFECT DUE TOFAST DEMAND RESPONSEFOR BUILD...ijccmsjournal
In order to evaluate side-effect of power limitation due to the Fast Automated Demand Response
(FastADR) for building air-conditioning facilities, a prediction model on short time change of average
room temperature has been developed. A room temperature indexis defined as a weighted average of the
entire building for room temperature deviations from the setpoints. The index is assumed to be used to
divide total FastADRrequest to distribute power limitation commands to each building.In order to predict
five-minute-change of the index, our combined mathematical model of an auto regression (AR) and a
neural network (NN) is proposed.In the experimental results, the combined model showedthe root mean
square error (RMSE) of 0.23 degrees, in comparison with 0.37 and 0.26 for conventional single NN and AR
models, respectively. This result is satisfactory prediction for required comfort of approximately 1 degree
Celsius allowance.
A SEW-EURODRIVE brake repair kit is needed for maintenance and repair of specific SEW-EURODRIVE brake models, like the BE series. It includes all necessary parts for preventative maintenance and repairs. This ensures proper brake functionality and extends the lifespan of the brake system
This study will provide the audience with an understanding of the capabilities of soft tools such as Artificial Neural Networks (ANN), Support Vector Regression (SVR), Model Trees (MT), and Multi-Gene Genetic Programming (MGGP) as a statistical downscaling tool. Many projects are underway around the world to downscale the data from Global Climate Models (GCM). The majority of the statistical tools have a lengthy downscaling pipeline to follow. To improve its accuracy, the GCM data is re-gridded according to the grid points of the observed data, standardized, and, sometimes, bias-removal is required. The current work suggests that future precipitation can be predicted by using precipitation data from the nearest four grid points as input to soft tools and observed precipitation as output. This research aims to estimate precipitation trends in the near future (2021-2050), using 5 GCMs, for Pune, in the state of Maharashtra, India. The findings indicate that each one of the soft tools can model the precipitation with excellent accuracy as compared to the traditional method of Distribution Based Scaling (DBS). The results show that ANN models appear to give the best results, followed by MT, then MGGP, and finally SVR. This work is one of a kind in that it provides insights into the changing monsoon season in Pune. The anticipated average precipitation levels depict a rise of 300–500% in January, along with increases of 200-300% in February and March, and a 100-150% increase for April and December. In contrast, rainfall appears to be decreasing by 20-30% between June and September.
Rigor, ethics, wellbeing and resilience in the ICT doctoral journeyYannis
The doctoral thesis trajectory has been often characterized as a “long and windy road” or a journey to “Ithaka”, suggesting the promises and challenges of this journey of initiation to research. The doctoral candidates need to complete such journey (i) preserving and even enhancing their wellbeing, (ii) overcoming the many challenges through resilience, while keeping (iii) high standards of ethics and (iv) scientific rigor. This talk will provide a personal account of lessons learnt and recommendations from a senior researcher over his 30+ years of doctoral supervision and care for doctoral students. Specific attention will be paid on the special features of the (i) interdisciplinary doctoral research that involves Information and Communications Technologies (ICT) and other scientific traditions, and (ii) the challenges faced in the complex technological and research landscape dominated by Artificial Intelligence.
Call For Papers - International Journal on Natural Language Computing (IJNLC)kevig
Natural Language Processing is a programmed approach to analyze text that is based on both a
set of theories and a set of technologies. This forum aims to bring together researchers who have
designed and build software that will analyze, understand, and generate languages that humans use
naturally to address computers.
Impurities of Water and their Significance.pptxdhanashree78
Impart Taste, Odour, Colour, and Turbidity to water.
Presence of organic matter or industrial wastes or microorganisms (algae) imparts taste and odour to water.
Presence of suspended and colloidal matter imparts turbidity to water.
This research presents a machine learning (ML) based model to estimate the axial strength of corroded RC columns reinforced with fiber-reinforced polymer (FRP) composites. Estimating the axial strength of corroded columns is complex due to the intricate interplay between corrosion and FRP reinforcement. To address this, a dataset of 102 samples from various literature sources was compiled. Subsequently, this dataset was employed to create and train the ML models. The parameters influencing axial strength included the geometry of the column, properties of the FRP material, degree of corrosion, and properties of the concrete. Considering the scarcity of reliable design guidelines for estimating the axial strength of RC columns considering corrosion effects, artificial neural network (ANN), Gaussian process regression (GPR), and support vector machine (SVM) techniques were employed. These techniques were used to predict the axial strength of corroded RC columns reinforced with FRP. When comparing the results of the proposed ML models with existing design guidelines, the ANN model demonstrated higher predictive accuracy. The ANN model achieved an R-value of 98.08% and an RMSE value of 132.69 kN which is the lowest among all other models. This model fills the existing gap in knowledge and provides a precise means of assessment. This model can be used in the scientific community by researchers and practitioners to predict the axial strength of FRP-strengthened corroded columns. In addition, the GPR and SVM models obtained an accuracy of 98.26% and 97.99%, respectively.
Civil engineering faces significant challenges from expansive soils, which can lead to structural damage. This study aims to optimize subtractive clustering and Fuzzy C-Mean Clustering (FCM) models for the most accurate prediction of swelling percentage in expansive soils. Two ANFIS models were developed, namely the FIS1S model using subtractive clustering and the FIS2S model utilizing the FCM algorithm. Due to the MATLAB graphical user interface's limitation on the number of membership functions, the coding approach was employed to develop the ANFIS models for optimal prediction accuracy and problem-solving time. So, two programs were created to determine the optimal influence radius for the FIS1S model and the number of membership functions for the FIS2S model to achieve the highest prediction accuracy. The ANFIS models have demonstrated their highest predictive ability in predicting swelling percentage, thanks to the optimization of membership functions and cluster centers. The developed programs also showed excellent performance and can be potentially applied to optimize subtractive clustering and FCM models in accurately modeling various engineering aspects.
1. RAISONI GROUP OF INSTITUTIONS
Presentation
On
“Programming with Python”
By
Ms. H. C Kunwar
Assistant Professor
Department of Computer Engineering
G. H. Raisoni Polytechnic, Nagpur.
RAISONI GROUP OF INSTITUTIONS 1
2. RAISONI GROUP OF INSTITUTIONS 2
Department of Computer Engineering
Unit 5
(12 Marks)
Object Oriented Programming in Python
Lecture-1
3. RAISONI GROUP OF INSTITUTIONS 3
5.1 Creating Classes & Objects in Python
Python Objects and Classes :
Python is an object oriented programming language. Unlike procedure oriented
programming, where the main emphasis is on functions, object oriented programming
stresses on objects.
An object is simply a collection of data (variables) and methods (functions) that act
on those data. An object is also called an instance of a class and the process of
creating this object is called instantiation.
A class is a blueprint for that object. As many houses can be made from a house's
blueprint, we can create many objects from a class.
For Example : We can think of class as a sketch (prototype) of a house. It contains
all the details about the floors, doors, windows etc. Based on these descriptions we
build the house. House is the object.
4. RAISONI GROUP OF INSTITUTIONS 4
5.1 Creating Classes & Objects in Python
Defining a Class in Python :
Like function definitions begin with the def keyword in Python, class definitions
begin with a class keyword.
The first string inside the class is called docstring and has a brief description
about the class. Although not mandatory, this is highly recommended.
Here is a simple class definition.
A class creates a new local namespace where all its attributes are defined.
Attributes may be data or functions.
There are also special attributes in it that begins with double underscores __. For
example, __doc__ gives us the docstring of that class.
As soon as we define a class, a new class object is created with the same name.
This class object allows us to access the different attributes as well as to
instantiate new objects of that class.
class MyNewClass:
'''This is a docstring. I have created a new class'''
pass
5. RAISONI GROUP OF INSTITUTIONS 5
5.1 Creating Classes & Objects in Python
Example :
class Person:
"This is a person class"
age = 10
def greet(self):
print('Hello')
# Output: 10
print(Person.age)
# Output: <function Person.greet>
print(Person.greet)
# Output: 'This is my second class'
print(Person.__doc__)
Output
10
<function Person.greet at 0x7fc78c6e8160>
This is a person class
6. RAISONI GROUP OF INSTITUTIONS 6
5.1 Creating an Objects in Python
Creating an Object in Python :
We saw that the class object could be used to access different attributes.
It can also be used to create new object instances (instantiation) of that class. The
procedure to create an object is similar to a function call.
>>> harry = Person()
This will create a new object instance named harry. We can access the attributes of
objects using the object name prefix.
Attributes may be data or method. Methods of an object are corresponding
functions of that class.
This means to say, since Person.greet is a function object (attribute of class),
Person.greet will be a method object.
7. RAISONI GROUP OF INSTITUTIONS 7
5.1 Creating Objects in Python
Example :
class Person:
"This is a person class"
age = 10
def greet(self):
print('Hello')
# create a new object of Person class
harry = Person()
# Output: <function Person.greet>
print(Person.greet)
# Output: <bound method Person.greet of
<__main__.Person object>>
print(harry.greet)
# Calling object's greet() method
# Output: Hello
harry.greet()
Output :
<function Person.greet at
0x7fd288e4e160>
<bound method Person.greet of
<__main__.Person object at
0x7fd288e9fa30>>
Hello
8. RAISONI GROUP OF INSTITUTIONS 8
5.1 Creating Objects in Python
Explanation :
You may have noticed the self parameter in function definition inside the class
but we called the method simply as harry.greet() without any arguments. It still
worked.
This is because, whenever an object calls its method, the object itself is passed as
the first argument. So, harry.greet() translates into Person.greet(harry).
In general, calling a method with a list of n arguments is equivalent to calling the
corresponding function with an argument list that is created by inserting the
method's object before the first argument.
For these reasons, the first argument of the function in class must be the object
itself. This is conventionally called self. It can be named otherwise but we highly
recommend to follow the convention.
9. RAISONI GROUP OF INSTITUTIONS 9
5.1 Creating Objects in Python
Example :
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " +
self.name)
p1 = Person("John", 36)
p1.myfunc()
Output :
Hello my name is John
Note: The self parameter is a reference to the current instance of the class, and is used
to access variables that belong to the class.
10. RAISONI GROUP OF INSTITUTIONS 10
5.1 Creating Objects in Python
The self Parameter :
The self parameter is a reference to the current instance of the class, and is used to
access variables that belongs to the class.
It does not have to be named self , you can call it whatever you like, but it has to
be the first parameter of any function in the class:
Example :
Use the words mysillyobject and abc instead of self:
class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()
Output :
Hello my name is John
11. RAISONI GROUP OF INSTITUTIONS 11
Constructors in Python :
Class functions that begin with double underscore __ are called special functions as
they have special meaning.
Of one particular interest is the __init__() function. This special function gets called
whenever a new object of that class is instantiated.
This type of function is also called constructors in Object Oriented Programming
(OOP). We normally use it to initialize all the variables.
class ComplexNumber:
def __init__(self, r=0, i=0):
self.real = r
self.imag = i
def get_data(self):
print(f'{self.real}+{self.imag}j')
5.1 Creating Constructors in Python
12. RAISONI GROUP OF INSTITUTIONS 12
5.1 Creating Constructors in Python
Output :
2+3j
(5, 0, 10)
Traceback (most recent call last):
File "<string>", line 27, in
<module>
print(num1.attr)
AttributeError: 'ComplexNumber'
object has no attribute 'attr'
13. RAISONI GROUP OF INSTITUTIONS 13
5.1 Deleting Attributes and Objects in Python
Deleting Attributes and Objects :
Any attribute of an object can be deleted anytime, using the del
statement.
>>> num1 = ComplexNumber(2,3)
>>> del num1.imag
>>> num1.get_data()
Traceback (most recent call last):
...
AttributeError: 'ComplexNumber' object has no attribute 'imag‘
>>> del ComplexNumber.get_data
>>> num1.get_data()
Traceback (most recent call last):
...
AttributeError: 'ComplexNumber' object has no attribute 'get_data'
14. RAISONI GROUP OF INSTITUTIONS 14
5.1 Creating Constructors in Python
We can even delete the object itself, using the del statement.
>>> c1 = ComplexNumber(1,3)
>>> del c1
>>> c1
Traceback (most recent call last):
...
NameError: name 'c1' is not defined
Actually, it is more complicated than that. When we do c1 =
ComplexNumber(1,3), a new instance object is created in memory and the name
c1 binds with it.
On the command del c1, this binding is removed and the name c1 is deleted from
the corresponding namespace. The object however continues to exist in memory
and if no other name is bound to it, it is later automatically destroyed.
This automatic destruction of unreferenced objects in Python is also called
garbage collection.
15. RAISONI GROUP OF INSTITUTIONS 15
5.2 Method Overloading in Python
Method Overloading :
Method Overloading is an
example of Compile time
polymorphism. In this, more
than one method of the same
class shares the same
method name having
different signatures. Method
overloading is used to add
more to the behavior of
methods and there is no
need of more than one class
for method overloading.
Note: Python does not
support method
overloading. We may
overload the methods but
can only use the latest
defined method.
# Function to take multiple arguments
def add(datatype, *args):
# if datatype is int # initialize answer as 0
if datatype =='int':
answer = 0
# if datatype is str # initialize answer as ''
if datatype =='str':
answer =''
# Traverse through the arguments
for x in args:
# This will do addition if the # arguments are int. Or
concatenation # if the arguments are str
answer = answer + x
print(answer)
# Integer
add('int', 5, 6)
# String
add('str', 'Hi ', 'Geeks') Output:
Output :
11
Hi Geeks
16. RAISONI GROUP OF INSTITUTIONS 16
5.1 Method Overloading in Python ?
Example :
class Employee :
def Hello_Emp(self,e_name=None):
if e_name is not None:
print("Hello "+e_name)
else:
print("Hello ")
emp1=Employee()
emp1.Hello_Emp()
emp1.Hello_Emp("Besant")
Output :
Hello
Hello Besant
Example:
class Area:
def find_area(self,a=None,b=None):
if a!=None and b!=None:
print("Area of Rectangle:",(a*b))
elif a!=None:
print("Area of square:",(a*a))
else:
print("Nothing to find")
obj1=Area()
obj1.find_area()
obj1.find_area(10)
obj1.find_area(10,20)
Output:
Nothing to find Area of a square: 100
Area of Rectangle: 200
17. RAISONI GROUP OF INSTITUTIONS 17
5.2 Method Overriding in Python ?
Method Overriding :
1. Method overriding is an example of run time polymorphism.
2. In this, the specific implementation of the method that is already provided
by the parent class is provided by the child class.
3. It is used to change the behavior of existing methods and there is a need for
at least two classes for method overriding.
4. In method overriding, inheritance always required as it is done between
parent class(superclass) and child class(child class) methods.
18. RAISONI GROUP OF INSTITUTIONS 18
5.2 Method Overriding in Python ?
class A:
def fun1(self):
print('feature_1 of class A')
def fun2(self):
print('feature_2 of class A')
class B(A):
# Modified function that is
# already exist in class A
def fun1(self):
print('Modified feature_1 of class A by class B')
def fun3(self):
print('feature_3 of class B')
# Create instance
obj = B()
# Call the override function
obj.fun1()
Output:
Modified version of
feature_1 of class A
by class B
19. RAISONI GROUP OF INSTITUTIONS 19
5.2 Method Overriding in Python ?
#Example : Python Method Overriding
class Employee:
def message(self):
print('This message is from Employee Class')
class Department(Employee):
def message(self):
print('This Department class is inherited from
Employee')
emp = Employee()
emp.message()
print('------------')
dept = Department()
dept.message()
Output :
20. RAISONI GROUP OF INSTITUTIONS 20
5.2 Method Overriding in Python ?
Example :
class Employee:
def message(self):
print('This message is from Employee Class')
class Department(Employee):
def message(self):
print('This Department class is inherited from Employee')
class Sales(Employee):
def message(self):
print('This Sales class is inherited from Employee')
emp = Employee()
emp.message()
print('------------')
dept = Department()
dept.message()
print('------------')
sl = Sales()
sl.message()
Output :
21. RAISONI GROUP OF INSTITUTIONS 21
5.2 Method Overriding in Python ?
Sr. No. Method Overloading Method Overriding
1 Method overloading is a compile time
polymorphism
Method overriding is a run time
polymorphism.
2 It help to rise the readability of the
program.
While it is used to grant the
specific implementation of the
method which is already provided
by its parent class or super class.
3 It is occur within the class. While it is performed in two
classes with inheritance
relationship.
4 Method overloading may or may not
require inheritance.
While method overriding always
needs inheritance.
5 In this, methods must have same
name and different signature.
While in this, methods must have
same name and same signature.
6 In method overloading, return type
can or can not be same, but we must
have to change the parameter.
While in this, return type must be
same or co-variant.
22. RAISONI GROUP OF INSTITUTIONS 22
5.3 Data Hiding in Python ?
Data Hiding :
Data hiding in Python is the method to prevent access to specific users in the
application. Data hiding in Python is done by using a double underscore before
(prefix) the attribute name. This makes the attribute private/ inaccessible and hides
them from users.
Data hiding ensures exclusive data access to class members and protects object
integrity by preventing unintended or intended changes.
Example :
class MyClass:
__hiddenVar = 12
def add(self, increment):
self.__hiddenVar += increment
print (self.__hiddenVar)
myObject = MyClass()
myObject.add(3)
myObject.add (8)
print (myObject._MyClass__hiddenVar)
Output
15
23
23
23. RAISONI GROUP OF INSTITUTIONS 23
5.3 Data Hiding in Python ?
Data Hiding :
Data hiding
In Python, we use double underscore before the attributes name to make them
inaccessible/private or to hide them.
The following code shows how the variable __hiddenVar is hidden.
Example :
class MyClass:
__hiddenVar = 0
def add(self, increment):
self.__hiddenVar += increment
print (self.__hiddenVar)
myObject = MyClass()
myObject.add(3)
myObject.add (8)
print (myObject.__hiddenVar)
Output
3
Traceback (most recent call last):
11
File "C:/Users/TutorialsPoint1/~_1.py",
line 12, in <module>
print (myObject.__hiddenVar)
AttributeError: MyClass instance has no
attribute '__hiddenVar'
In the above program, we tried to access
hidden variable outside the class using
object and it threw an exception.
24. RAISONI GROUP OF INSTITUTIONS 24
5.4 Data Abstraction in Python ?
Data Abstraction :
Abstraction in Python is the process of hiding the real implementation of an
application from the user and emphasizing only on usage of it. For example,
consider you have bought a new electronic gadget.
Syntax :
25. RAISONI GROUP OF INSTITUTIONS 25
5.4 Data Abstraction in Python ?
Example :
from abc import ABC, abstractmethod
class Absclass(ABC):
def print(self,x):
print("Passed value: ", x)
@abstractmethod
def task(self):
print("We are inside Absclass task")
class test_class(Absclass):
def task(self):
print("We are inside test_class task")
class example_class(Absclass):
def task(self):
print("We are inside example_class task")
#object of test_class created
test_obj = test_class()
test_obj.task()
test_obj.print(100)
#object of example_class created
example_obj = example_class()
example_obj.task()
example_obj.print(200)
print("test_obj is instance of Absclass? ", isinstance(test_obj, Absclass))
26. RAISONI GROUP OF INSTITUTIONS 26
5.4 Data Abstraction in Python ?
Output :
27. RAISONI GROUP OF INSTITUTIONS 27
5.5 Inheritance & composition classes in Python ?
What is Inheritance (Is-A Relation) :
It is a concept of Object-Oriented Programming. Inheritance is a mechanism that
allows us to inherit all the properties from another class. The class from which the
properties and functionalities are utilized is called the parent class (also called as
Base Class). The class which uses the properties from another class is called as Child
Class (also known as Derived class). Inheritance is also called an Is-A Relation.
28. RAISONI GROUP OF INSTITUTIONS 28
5.5 Inheritance & composition classes in Python ?
Syntax :
# Parent class
class Parent :
# Constructor
# Variables of Parent class
# Methods
...
...
# Child class inheriting Parent class
class Child(Parent) :
# constructor of child class
# variables of child class
# methods of child class
29. RAISONI GROUP OF INSTITUTIONS 29
5.5 Inheritance & composition classes in Python ?
# parent class
class Parent:
# parent class method
def m1(self):
print('Parent Class Method called...')
# child class inheriting parent class
class Child(Parent):
# child class constructor
def __init__(self):
print('Child Class object created...')
# child class method
def m2(self):
print('Child Class Method called...')
# creating object of child class
obj = Child()
# calling parent class m1() method
obj.m1()
# calling child class m2() method
obj.m2()
Output :
Child Class object created...
Parent Class Method called...
Child Class Method called...
30. RAISONI GROUP OF INSTITUTIONS 30
5.5 Inheritance & composition classes in Python ?
What is Composition (Has-A Relation) :
It is one of the fundamental concepts of
Object-Oriented Programming.
In this we will describe a class that
references to one or more objects of other
classes as an Instance variable.
Here, by using the class name or by creating
the object we can access the members of one
class inside another class.
It enables creating complex types by
combining objects of different classes.
It means that a class Composite can contain
an object of another class Component.
This type of relationship is known as Has-A
Relation.
31. RAISONI GROUP OF INSTITUTIONS 31
5.5 Inheritance & composition classes in Python ?
Syntax :
class A :
# variables of class A
# methods of class A
...
...
class B :
# by using "obj" we can access member's of class A.
obj = A()
# variables of class B
# methods of class B
...
...
32. RAISONI GROUP OF INSTITUTIONS 32
5.5 Inheritance & composition classes in Python ?
class Component:
# composite class constructor
def __init__(self):
print('Component class object created...')
# composite class instance method
def m1(self):
print('Component class m1() method executed...')
class Composite:
# composite class constructor
def __init__(self):
# creating object of component class
self.obj1 = Component()
print('Composite class object also created...')
# composite class instance method
def m2(self):
print('Composite class m2() method executed...')
# calling m1() method of component class
self.obj1.m1()
# creating object of composite class
obj2 = Composite()
# calling m2() method of composite class
obj2.m2()
33. RAISONI GROUP OF INSTITUTIONS 33
5.6 Customization via inheritance specializing
inherited methods in Python ?
Customization via Inheritance specializing inherited methods:
1. The tree-searching model of inheritance turns out to be a great way to specialize
systems. Because inheritance finds names in subclasses before it checks
superclasses, subclasses can replace default behavior by redefining the
superclass's attributes.
2. In fact, you can build entire systems as hierarchies of classes, which are
extended by adding new external subclasses rather than changing existing logic
in place.
3. The idea of redefining inherited names leads to a variety of specialization
techniques.
1. For instance, subclasses may replace inherited attributes completely, provide
attributes that a superclass expects to find, and extend superclass methods by
calling back to the superclass from an overridden method.
34. RAISONI GROUP OF INSTITUTIONS 34
5.6 Customization via inheritance specializing
inherited methods in Python ?
Example- For specilaized inherited methods
class A:
"parent class" #parent class
def display(self):
print("This is base class")
class B(A):
"Child class" #derived class
def display(self):
A.display(self)
print("This is derived class")
obj=B() #instance of child
obj.display() #child calls overridden method
Output:
This is base class
This is derived class