SlideShare a Scribd company logo
3
#Class Constructor Function
class Employee:
#Common base class for all employees
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employee %d" ,Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
#Creating Instance Object
emp1 = Employee("Zara", 2000)
emp2 = Employee("Manni", 5000)
#Accessing Object
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount
The first method __init__() is a
special method, which is called
class constructor or initialization
method that Python calls when
you create a new instance of this
class.
To create instances of a class, you
call the class using class name and
pass in whatever arguments
its __init__ method accepts.
You access the object's attributes
using the dot operator with object.
Class variable would be accessed
using class name as follows −
Most read
20
It’s Work If Different Arguments as a
Parameter
# 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')
Most read
22
What is __MetaClass__ ?
Most read
Overview of OOP Terminology
Class − A user-defined prototype for an object that defines a set of
attributes that characterize any object of the class. The attributes
are data members (class variables and instance variables) and
methods, accessed via dot notation.
Class variable − A variable that is shared by all instances of a class.
Class variables are defined within a class but outside any of the
class's methods. Class variables are not used as frequently as
instance variables are.
Data member − A class variable or instance variable that holds data
associated with a class and its objects.
Function overloading − The assignment of more than one behavior
to a particular function. The operation performed varies by the
types of objects or arguments involved.
• Instance variable − A variable that is defined inside a method
and belongs only to the current instance of a class.
• Inheritance − The transfer of the characteristics of a class to other
classes that are derived from it.
• Instance − An individual object of a certain class. An object obj that
belongs to a class Circle, for example, is an instance of the class
Circle.
• Method − A special kind of function that is defined in a class
definition.
• Object − A unique instance of a data structure that's defined by its
class. An object comprises both data members (class variables and
instance variables) and methods.
• Operator overloading − The assignment of more than one function
to a particular operator.
#Class Constructor Function
class Employee:
#Common base class for all employees
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employee %d" ,Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
#Creating Instance Object
emp1 = Employee("Zara", 2000)
emp2 = Employee("Manni", 5000)
#Accessing Object
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount
The first method __init__() is a
special method, which is called
class constructor or initialization
method that Python calls when
you create a new instance of this
class.
To create instances of a class, you
call the class using class name and
pass in whatever arguments
its __init__ method accepts.
You access the object's attributes
using the dot operator with object.
Class variable would be accessed
using class name as follows −
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print ("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary)
"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print ("Total Employee %d" % Employee.empCount)
Calc Via Class
class cal():
def __init__(self,a,b):
self.a=a
self.b=b
def add(self):
return self.a+self.b
def mul(self):
return self.a*self.b
def div(self):
return self.a/self.b
def sub(self):
return self.a-self.b
a=int(input("Enter first number: "))
b=int(input("Enter second number: "))
obj=cal(a,b)
choice=1
while choice!=0:
print("0. Exit")
print("1. Add")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
choice=int(input("Enter choice: "))
if choice==1:
print("Result: ",obj.add())
elif choice==2:
print("Result: ",obj.sub())
elif choice==3:
print("Result: ",obj.mul())
elif choice==4:
print("Result: ",round(obj.div(),2))
elif choice==0:
print("Exiting!")
else:
print("Invalid choice!!")
print()
Built-In Class Attributes
Every Python class keeps following built-in attributes and they can be
accessed using dot operator like any other attribute −
• __dict__ − Dictionary containing the class's namespace.
• __doc__ − Class documentation string or none, if undefined.
• __name__ − Class name.
• __module__ − Module name in which the class is defined. This
attribute is "__main__" in interactive mode.
• __bases__ − A possibly empty tuple containing the base classes, in
the order of their occurrence in the base class list.
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print ("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary)
print ("Employee.__doc__:", Employee.__doc__)
print ("Employee.__name__:", Employee.__name__)
print ("Employee.__module__:", Employee.__module__)
print ("Employee.__bases__:", Employee.__bases__)
print ("Employee.__dict__:", Employee.__dict__)
Destroying Objects (Garbage Collection) / Destruction
• Python deletes unneeded objects (built-in types or class
instances) automatically to free the memory space. The
process by which Python periodically reclaims blocks of
memory that no longer are in use is termed Garbage
Collection.
• Python's garbage collector runs during program execution
and is triggered when an object's reference count reaches
zero. An object's reference count changes as the number of
aliases that point to it changes.
• You normally will not notice when the garbage collector
destroys an orphaned instance and reclaims its space. But a
class can implement the special method __del__(), called a
destructor, that is invoked when the instance is about to be
destroyed. This method might be used to clean up any non
memory resources used by an instance.
class Point:
def __init__( self, x=0, y=0):
self.x = x
self.y = y
def __del__(self):
class_name = self.__class__.__name__
print (class_name, "destroyed")
pt1 = Point()
pt2 = pt1
pt3 = pt1
print (id(pt1), id(pt2), id(pt3)) # prints the ids of the obejcts
del pt1
del pt2
del pt3
Class Inheritance
• Instead of starting from scratch, you can create a class by deriving it
from a preexisting class by listing the parent class in parentheses
after the new class name.
• The child class inherits the attributes of its parent class, and you can
use those attributes as if they were defined in the child class. A
child class can also override data members and methods from the
parent.
Syntax
• Derived classes are declared much like their parent class; however,
a list of base classes to inherit from is given after the class name −
class SubClassName (ParentClass1[, ParentClass2, ...]):
'Optional class documentation string‘
Get And SET Attribute
Get and set attribute of objects.
The syntax of setattr() method is:
setattr(object, name, value)
setattr() Parameters
The setattr() method takes three parameters
• object - object whose attribute has to be set
• name - string which contains the name of the
attribute to be set
• value - value of the attribute to be set
class Person:
name = 'Adam'
p = Person()
print('Before modification:', p.name)
# setting name to 'John‘
setattr(p, 'name', 'John')
print('After modification:', p.name)
#Mainly GET and SET used for ….
class Person:
name = 'Adam'
p = Person()
# setting attribute name to None
setattr(p, 'name', None)
print('Name is:', p.name)
# setting an attribute not present
# in Person
setattr(p, 'age', 23)
print('Age is:', p.age)
Get Attribute
The getattr() method returns the value of the named attribute of an object. If not
found, it returns the default value provided to the function.
• The syntax of getattr() method is:
getattr(object, name[, default])
getattr() Parameters
The getattr() method takes multiple parameters:
• object - object whose named attribute's value is to be returned
• name - string that contains the attribute's name
• default (Optional) - value that is returned when the named attribute is not
found
#E.G.
class Person:
age = 23
name = "Adam“
person = Person()
# when default value is provided
print('The gender is:', getattr(person, 'gender', 'Male'))
# when no default value is provided
print('The gender is:', getattr(person, 'gender'))
#Inheritance Example
class Parent: # define parent class
parentAttr = 100
def __init__(self):
print ("Calling parent constructor")
def parentMethod(self):
print ('Calling parent method')
def setAttr(self, attr):
Parent.parentAttr = attr
def getAttr(self):
print ("Parent attribute :", Parent.parentAttr)
class Child(Parent): # define child class
def __init__(self):
print ("Calling child constructor")
def childMethod(self):
print ('Calling child method')
c = Child() # instance of child
c.childMethod() # child calls its method
c.parentMethod() # calls parent's method
c.setAttr(200) # again call parent's method
c.getAttr() # again call parent's method
Overriding Methods
- You can always override your parent class methods. One reason for
overriding parent's methods is because you may want special or
different functionality in your subclass.
• Example
class Parent: # define parent class
def myMethod(self):
print ('Calling parent method vadil')
class Child(Parent): # define child class
def myMethod(self):
print ('Calling child method 6okrav')
c = Child() # instance of child
c.myMethod() # child calls overridden method
What is MRO ?
• A class can be derived from more than one base classes in Python.
This is called multiple inheritance.
• In multiple inheritance, the features of all the base classes are
inherited into the derived class. The syntax for multiple inheritance
is similar to single inheritance.
E.g.. class Super1:
pass
class Super2:
pass
class MultiDerived(Super1, Super2):
pass
- In the multiple inheritance scenario, any specified attribute is searched
first in the current class. If not found, the search continues into parent
classes in depth-first, left-right fashion without searching same class
twice.
- MRO Stand for Method resolution Order.
• So, in the above example of MultiDerived class
the search order is [MultiDerived, Super1,
Super2, object]. This order is also called
linearization of MultiDerived class and the set
of rules used to find this order is called
Method Resolution Order (MRO).
• MRO ensures that a class always appears
before its parents and in case of multiple
parents, the order is same as tuple of base
classes.
Duck Typing
• Duck typing is a concept that says that the “type”
of the object is a matter of concern only at
runtime and you don’t need to to explicitly
mention the type of the object before you
perform nay kind of operation on that object.
• You don’t need to define the type of things like
int,float etc…its called duck typing.
• The following example can help in understanding
this concept -
• def calc(a,b):
• return a+b
Method Overloading
• Same name different arguments in method that
is called an method overloading.
• Python doesn’t support method overloading but
if we want to do then we can do as per below.
### Error
def product(a, b):
p = a * b
print(p)
def product(a, b, c):
p = a * b*c
print(p)
#product(4, 5)
product(4, 5, 5)
It’s Work If Different Arguments as a
Parameter
# 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')
Abstract Class
Abstract classes: Force a class to implement
methods.
Abstract classes can contain abstract methods:
methods without an implementation.
Objects cannot be created from an abstract class.
A subclass can implement an abstract class.
Meaning of @
This shows that the function/method/class
you're defining after a decorator is just basically
passed on as an argument to the
function/method immediately after the @ sign.
What is __MetaClass__ ?
import abc
class AbstractAnimal(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def walk(self):
''' data '''
@abc.abstractmethod
def talk(self):
''' data '''
class Duck(AbstractAnimal):
name = ''
def __init__(self, name):
print('duck created.')
self.name = name
def walk(self):
print('walks')
def talk(self):
print('quack')
obj = Duck('duck1')
obj.talk()
obj.walk()
Done Till Mid
Your Task
• Different between interface and abstract class ?
My Task
• Revision Of 3 Chapter
• Write the question answer of 3 chapter.
• IMP question of mid
• Example of library program

More Related Content

What's hot (20)

Chapter 07 inheritance
Chapter 07 inheritanceChapter 07 inheritance
Chapter 07 inheritance
Praveen M Jigajinni
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with python
Arslan Arshad
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
TMARAGATHAM
 
Python OOPs
Python OOPsPython OOPs
Python OOPs
Binay Kumar Ray
 
Python programming : Arrays
Python programming : ArraysPython programming : Arrays
Python programming : Arrays
Emertxe Information Technologies Pvt Ltd
 
Object Oriented Programming in Python
Object Oriented Programming in PythonObject Oriented Programming in Python
Object Oriented Programming in Python
Sujith Kumar
 
String Handling in c++
String Handling in c++String Handling in c++
String Handling in c++
Fahim Adil
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
Santosh Verma
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
baabtra.com - No. 1 supplier of quality freshers
 
Python Modules
Python ModulesPython Modules
Python Modules
Nitin Reddy Katkam
 
Python programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphismPython programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphism
Emertxe Information Technologies Pvt Ltd
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
moazamali28
 
Namespaces
NamespacesNamespaces
Namespaces
Sangeetha S
 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
Kamal Acharya
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
Devashish Kumar
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
Gurpreet singh
 
Python Generators
Python GeneratorsPython Generators
Python Generators
Akshar Raaj
 
Database connectivity in python
Database connectivity in pythonDatabase connectivity in python
Database connectivity in python
baabtra.com - No. 1 supplier of quality freshers
 
Data Analysis in Python-NumPy
Data Analysis in Python-NumPyData Analysis in Python-NumPy
Data Analysis in Python-NumPy
Devashish Kumar
 
Generics
GenericsGenerics
Generics
Ravi_Kant_Sahu
 

Similar to PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA (20)

جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
Mohammad Reza Kamalifard
 
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونیاسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
Mohammad Reza Kamalifard
 
Python advance
Python advancePython advance
Python advance
Mukul Kirti Verma
 
Python classes objects
Python classes objectsPython classes objects
Python classes objects
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Python session 7 by Shan
Python session 7 by ShanPython session 7 by Shan
Python session 7 by Shan
Navaneethan Naveen
 
Presentation_4516_Content_Document_20250204010703PM.pptx
Presentation_4516_Content_Document_20250204010703PM.pptxPresentation_4516_Content_Document_20250204010703PM.pptx
Presentation_4516_Content_Document_20250204010703PM.pptx
MuhammadChala
 
Basic_concepts_of_OOPS_in_Python.pptx
Basic_concepts_of_OOPS_in_Python.pptxBasic_concepts_of_OOPS_in_Python.pptx
Basic_concepts_of_OOPS_in_Python.pptx
santoshkumar811204
 
Python Lecture 13
Python Lecture 13Python Lecture 13
Python Lecture 13
Inzamam Baig
 
Object Oriented Programming.pptx
Object Oriented Programming.pptxObject Oriented Programming.pptx
Object Oriented Programming.pptx
SAICHARANREDDYN
 
Lecture topic - Python class lecture.ppt
Lecture topic - Python class lecture.pptLecture topic - Python class lecture.ppt
Lecture topic - Python class lecture.ppt
Reji K Dhaman
 
Lecture on Python class -lecture123456.ppt
Lecture on Python class -lecture123456.pptLecture on Python class -lecture123456.ppt
Lecture on Python class -lecture123456.ppt
Reji K Dhaman
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Three
amiable_indian
 
Chap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.pptChap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.ppt
muneshwarbisen1
 
Object_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdfObject_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdf
Koteswari Kasireddy
 
IPP-M5-C1-Classes _ Objects python -S2.pptx
IPP-M5-C1-Classes _ Objects python -S2.pptxIPP-M5-C1-Classes _ Objects python -S2.pptx
IPP-M5-C1-Classes _ Objects python -S2.pptx
DhavalaShreeBJain
 
Python_Object_Oriented_Programming.pptx
Python_Object_Oriented_Programming.pptxPython_Object_Oriented_Programming.pptx
Python_Object_Oriented_Programming.pptx
Koteswari Kasireddy
 
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptxPYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
mru761077
 
Python3
Python3Python3
Python3
Ruchika Sinha
 
object oriented programming(PYTHON)
object oriented programming(PYTHON)object oriented programming(PYTHON)
object oriented programming(PYTHON)
Jyoti shukla
 
Unit – V Object Oriented Programming in Python.pptx
Unit – V Object Oriented Programming in Python.pptxUnit – V Object Oriented Programming in Python.pptx
Unit – V Object Oriented Programming in Python.pptx
YugandharaNalavade
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
Mohammad Reza Kamalifard
 
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونیاسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
Mohammad Reza Kamalifard
 
Presentation_4516_Content_Document_20250204010703PM.pptx
Presentation_4516_Content_Document_20250204010703PM.pptxPresentation_4516_Content_Document_20250204010703PM.pptx
Presentation_4516_Content_Document_20250204010703PM.pptx
MuhammadChala
 
Basic_concepts_of_OOPS_in_Python.pptx
Basic_concepts_of_OOPS_in_Python.pptxBasic_concepts_of_OOPS_in_Python.pptx
Basic_concepts_of_OOPS_in_Python.pptx
santoshkumar811204
 
Object Oriented Programming.pptx
Object Oriented Programming.pptxObject Oriented Programming.pptx
Object Oriented Programming.pptx
SAICHARANREDDYN
 
Lecture topic - Python class lecture.ppt
Lecture topic - Python class lecture.pptLecture topic - Python class lecture.ppt
Lecture topic - Python class lecture.ppt
Reji K Dhaman
 
Lecture on Python class -lecture123456.ppt
Lecture on Python class -lecture123456.pptLecture on Python class -lecture123456.ppt
Lecture on Python class -lecture123456.ppt
Reji K Dhaman
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Three
amiable_indian
 
Chap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.pptChap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.ppt
muneshwarbisen1
 
Object_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdfObject_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdf
Koteswari Kasireddy
 
IPP-M5-C1-Classes _ Objects python -S2.pptx
IPP-M5-C1-Classes _ Objects python -S2.pptxIPP-M5-C1-Classes _ Objects python -S2.pptx
IPP-M5-C1-Classes _ Objects python -S2.pptx
DhavalaShreeBJain
 
Python_Object_Oriented_Programming.pptx
Python_Object_Oriented_Programming.pptxPython_Object_Oriented_Programming.pptx
Python_Object_Oriented_Programming.pptx
Koteswari Kasireddy
 
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptxPYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
mru761077
 
object oriented programming(PYTHON)
object oriented programming(PYTHON)object oriented programming(PYTHON)
object oriented programming(PYTHON)
Jyoti shukla
 
Unit – V Object Oriented Programming in Python.pptx
Unit – V Object Oriented Programming in Python.pptxUnit – V Object Oriented Programming in Python.pptx
Unit – V Object Oriented Programming in Python.pptx
YugandharaNalavade
 
Ad

More from Maulik Borsaniya (7)

Dragon fruit-nutrition-facts
Dragon fruit-nutrition-factsDragon fruit-nutrition-facts
Dragon fruit-nutrition-facts
Maulik Borsaniya
 
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYAChapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Maulik Borsaniya
 
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYAPYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
Maulik Borsaniya
 
PYTHON - EXTRA Chapter GUI - MAULIK BORSANIYA
PYTHON - EXTRA Chapter GUI - MAULIK BORSANIYAPYTHON - EXTRA Chapter GUI - MAULIK BORSANIYA
PYTHON - EXTRA Chapter GUI - MAULIK BORSANIYA
Maulik Borsaniya
 
PYTHON-Chapter 4-Plotting and Data Science PyLab - MAULIK BORSANIYA
PYTHON-Chapter 4-Plotting and Data Science  PyLab - MAULIK BORSANIYAPYTHON-Chapter 4-Plotting and Data Science  PyLab - MAULIK BORSANIYA
PYTHON-Chapter 4-Plotting and Data Science PyLab - MAULIK BORSANIYA
Maulik Borsaniya
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
Maulik Borsaniya
 
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYAChapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Maulik Borsaniya
 
Dragon fruit-nutrition-facts
Dragon fruit-nutrition-factsDragon fruit-nutrition-facts
Dragon fruit-nutrition-facts
Maulik Borsaniya
 
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYAChapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Chapter 5 - THREADING & REGULAR exp - MAULIK BORSANIYA
Maulik Borsaniya
 
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYAPYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
Maulik Borsaniya
 
PYTHON - EXTRA Chapter GUI - MAULIK BORSANIYA
PYTHON - EXTRA Chapter GUI - MAULIK BORSANIYAPYTHON - EXTRA Chapter GUI - MAULIK BORSANIYA
PYTHON - EXTRA Chapter GUI - MAULIK BORSANIYA
Maulik Borsaniya
 
PYTHON-Chapter 4-Plotting and Data Science PyLab - MAULIK BORSANIYA
PYTHON-Chapter 4-Plotting and Data Science  PyLab - MAULIK BORSANIYAPYTHON-Chapter 4-Plotting and Data Science  PyLab - MAULIK BORSANIYA
PYTHON-Chapter 4-Plotting and Data Science PyLab - MAULIK BORSANIYA
Maulik Borsaniya
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
Maulik Borsaniya
 
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYAChapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Maulik Borsaniya
 
Ad

Recently uploaded (20)

Jeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software DeveloperJeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software Developer
Jeremy Millul
 
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Peter Bittner
 
Co-Constructing Explanations for AI Systems using Provenance
Co-Constructing Explanations for AI Systems using ProvenanceCo-Constructing Explanations for AI Systems using Provenance
Co-Constructing Explanations for AI Systems using Provenance
Paul Groth
 
Cyber Security Legal Framework in Nepal.pptx
Cyber Security Legal Framework in Nepal.pptxCyber Security Legal Framework in Nepal.pptx
Cyber Security Legal Framework in Nepal.pptx
Ghimire B.R.
 
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Aaryan Kansari
 
Dev Dives: System-to-system integration with UiPath API Workflows
Dev Dives: System-to-system integration with UiPath API WorkflowsDev Dives: System-to-system integration with UiPath API Workflows
Dev Dives: System-to-system integration with UiPath API Workflows
UiPathCommunity
 
Cybersecurity Fundamentals: Apprentice - Palo Alto Certificate
Cybersecurity Fundamentals: Apprentice - Palo Alto CertificateCybersecurity Fundamentals: Apprentice - Palo Alto Certificate
Cybersecurity Fundamentals: Apprentice - Palo Alto Certificate
VICTOR MAESTRE RAMIREZ
 
UiPath Community Zurich: Release Management and Build Pipelines
UiPath Community Zurich: Release Management and Build PipelinesUiPath Community Zurich: Release Management and Build Pipelines
UiPath Community Zurich: Release Management and Build Pipelines
UiPathCommunity
 
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Nikki Chapple
 
Securiport - A Border Security Company
Securiport  -  A Border Security CompanySecuriport  -  A Border Security Company
Securiport - A Border Security Company
Securiport
 
Improving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevExImproving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevEx
Justin Reock
 
Let’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack CommunityLet’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack Community
SanjeetMishra29
 
TrustArc Webinar: Mastering Privacy Contracting
TrustArc Webinar: Mastering Privacy ContractingTrustArc Webinar: Mastering Privacy Contracting
TrustArc Webinar: Mastering Privacy Contracting
TrustArc
 
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptxECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
Jasper Oosterveld
 
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Lorenzo Miniero
 
Evaluation Challenges in Using Generative AI for Science & Technical Content
Evaluation Challenges in Using Generative AI for Science & Technical ContentEvaluation Challenges in Using Generative AI for Science & Technical Content
Evaluation Challenges in Using Generative AI for Science & Technical Content
Paul Groth
 
Data Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any ApplicationData Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any Application
Safe Software
 
Maxx nft market place new generation nft marketing place
Maxx nft market place new generation nft marketing placeMaxx nft market place new generation nft marketing place
Maxx nft market place new generation nft marketing place
usersalmanrazdelhi
 
STKI Israel Market Study 2025 final v1 version
STKI Israel Market Study 2025 final v1 versionSTKI Israel Market Study 2025 final v1 version
STKI Israel Market Study 2025 final v1 version
Dr. Jimmy Schwarzkopf
 
European Accessibility Act & Integrated Accessibility Testing
European Accessibility Act & Integrated Accessibility TestingEuropean Accessibility Act & Integrated Accessibility Testing
European Accessibility Act & Integrated Accessibility Testing
Julia Undeutsch
 
Jeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software DeveloperJeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software Developer
Jeremy Millul
 
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Peter Bittner
 
Co-Constructing Explanations for AI Systems using Provenance
Co-Constructing Explanations for AI Systems using ProvenanceCo-Constructing Explanations for AI Systems using Provenance
Co-Constructing Explanations for AI Systems using Provenance
Paul Groth
 
Cyber Security Legal Framework in Nepal.pptx
Cyber Security Legal Framework in Nepal.pptxCyber Security Legal Framework in Nepal.pptx
Cyber Security Legal Framework in Nepal.pptx
Ghimire B.R.
 
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Aaryan Kansari
 
Dev Dives: System-to-system integration with UiPath API Workflows
Dev Dives: System-to-system integration with UiPath API WorkflowsDev Dives: System-to-system integration with UiPath API Workflows
Dev Dives: System-to-system integration with UiPath API Workflows
UiPathCommunity
 
Cybersecurity Fundamentals: Apprentice - Palo Alto Certificate
Cybersecurity Fundamentals: Apprentice - Palo Alto CertificateCybersecurity Fundamentals: Apprentice - Palo Alto Certificate
Cybersecurity Fundamentals: Apprentice - Palo Alto Certificate
VICTOR MAESTRE RAMIREZ
 
UiPath Community Zurich: Release Management and Build Pipelines
UiPath Community Zurich: Release Management and Build PipelinesUiPath Community Zurich: Release Management and Build Pipelines
UiPath Community Zurich: Release Management and Build Pipelines
UiPathCommunity
 
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Protecting Your Sensitive Data with Microsoft Purview - IRMS 2025
Nikki Chapple
 
Securiport - A Border Security Company
Securiport  -  A Border Security CompanySecuriport  -  A Border Security Company
Securiport - A Border Security Company
Securiport
 
Improving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevExImproving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevEx
Justin Reock
 
Let’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack CommunityLet’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack Community
SanjeetMishra29
 
TrustArc Webinar: Mastering Privacy Contracting
TrustArc Webinar: Mastering Privacy ContractingTrustArc Webinar: Mastering Privacy Contracting
TrustArc Webinar: Mastering Privacy Contracting
TrustArc
 
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptxECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
Jasper Oosterveld
 
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Multistream in SIP and NoSIP @ OpenSIPS Summit 2025
Lorenzo Miniero
 
Evaluation Challenges in Using Generative AI for Science & Technical Content
Evaluation Challenges in Using Generative AI for Science & Technical ContentEvaluation Challenges in Using Generative AI for Science & Technical Content
Evaluation Challenges in Using Generative AI for Science & Technical Content
Paul Groth
 
Data Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any ApplicationData Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any Application
Safe Software
 
Maxx nft market place new generation nft marketing place
Maxx nft market place new generation nft marketing placeMaxx nft market place new generation nft marketing place
Maxx nft market place new generation nft marketing place
usersalmanrazdelhi
 
STKI Israel Market Study 2025 final v1 version
STKI Israel Market Study 2025 final v1 versionSTKI Israel Market Study 2025 final v1 version
STKI Israel Market Study 2025 final v1 version
Dr. Jimmy Schwarzkopf
 
European Accessibility Act & Integrated Accessibility Testing
European Accessibility Act & Integrated Accessibility TestingEuropean Accessibility Act & Integrated Accessibility Testing
European Accessibility Act & Integrated Accessibility Testing
Julia Undeutsch
 

PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA

  • 1. Overview of OOP Terminology Class − A user-defined prototype for an object that defines a set of attributes that characterize any object of the class. The attributes are data members (class variables and instance variables) and methods, accessed via dot notation. Class variable − A variable that is shared by all instances of a class. Class variables are defined within a class but outside any of the class's methods. Class variables are not used as frequently as instance variables are. Data member − A class variable or instance variable that holds data associated with a class and its objects. Function overloading − The assignment of more than one behavior to a particular function. The operation performed varies by the types of objects or arguments involved.
  • 2. • Instance variable − A variable that is defined inside a method and belongs only to the current instance of a class. • Inheritance − The transfer of the characteristics of a class to other classes that are derived from it. • Instance − An individual object of a certain class. An object obj that belongs to a class Circle, for example, is an instance of the class Circle. • Method − A special kind of function that is defined in a class definition. • Object − A unique instance of a data structure that's defined by its class. An object comprises both data members (class variables and instance variables) and methods. • Operator overloading − The assignment of more than one function to a particular operator.
  • 3. #Class Constructor Function class Employee: #Common base class for all employees empCount = 0 def __init__(self, name, salary): self.name = name self.salary = salary Employee.empCount += 1 def displayCount(self): print "Total Employee %d" ,Employee.empCount def displayEmployee(self): print "Name : ", self.name, ", Salary: ", self.salary #Creating Instance Object emp1 = Employee("Zara", 2000) emp2 = Employee("Manni", 5000) #Accessing Object emp1.displayEmployee() emp2.displayEmployee() print "Total Employee %d" % Employee.empCount The first method __init__() is a special method, which is called class constructor or initialization method that Python calls when you create a new instance of this class. To create instances of a class, you call the class using class name and pass in whatever arguments its __init__ method accepts. You access the object's attributes using the dot operator with object. Class variable would be accessed using class name as follows −
  • 4. class Employee: 'Common base class for all employees' empCount = 0 def __init__(self, name, salary): self.name = name self.salary = salary Employee.empCount += 1 def displayCount(self): print ("Total Employee %d" % Employee.empCount) def displayEmployee(self): print ("Name : ", self.name, ", Salary: ", self.salary) "This would create first object of Employee class" emp1 = Employee("Zara", 2000) "This would create second object of Employee class" emp2 = Employee("Manni", 5000) emp1.displayEmployee() emp2.displayEmployee() print ("Total Employee %d" % Employee.empCount)
  • 5. Calc Via Class class cal(): def __init__(self,a,b): self.a=a self.b=b def add(self): return self.a+self.b def mul(self): return self.a*self.b def div(self): return self.a/self.b def sub(self): return self.a-self.b a=int(input("Enter first number: ")) b=int(input("Enter second number: ")) obj=cal(a,b) choice=1 while choice!=0: print("0. Exit") print("1. Add") print("2. Subtraction") print("3. Multiplication") print("4. Division") choice=int(input("Enter choice: ")) if choice==1: print("Result: ",obj.add()) elif choice==2: print("Result: ",obj.sub()) elif choice==3: print("Result: ",obj.mul()) elif choice==4: print("Result: ",round(obj.div(),2)) elif choice==0: print("Exiting!") else: print("Invalid choice!!") print()
  • 6. Built-In Class Attributes Every Python class keeps following built-in attributes and they can be accessed using dot operator like any other attribute − • __dict__ − Dictionary containing the class's namespace. • __doc__ − Class documentation string or none, if undefined. • __name__ − Class name. • __module__ − Module name in which the class is defined. This attribute is "__main__" in interactive mode. • __bases__ − A possibly empty tuple containing the base classes, in the order of their occurrence in the base class list.
  • 7. class Employee: 'Common base class for all employees' empCount = 0 def __init__(self, name, salary): self.name = name self.salary = salary Employee.empCount += 1 def displayCount(self): print ("Total Employee %d" % Employee.empCount) def displayEmployee(self): print ("Name : ", self.name, ", Salary: ", self.salary) print ("Employee.__doc__:", Employee.__doc__) print ("Employee.__name__:", Employee.__name__) print ("Employee.__module__:", Employee.__module__) print ("Employee.__bases__:", Employee.__bases__) print ("Employee.__dict__:", Employee.__dict__)
  • 8. Destroying Objects (Garbage Collection) / Destruction • Python deletes unneeded objects (built-in types or class instances) automatically to free the memory space. The process by which Python periodically reclaims blocks of memory that no longer are in use is termed Garbage Collection. • Python's garbage collector runs during program execution and is triggered when an object's reference count reaches zero. An object's reference count changes as the number of aliases that point to it changes. • You normally will not notice when the garbage collector destroys an orphaned instance and reclaims its space. But a class can implement the special method __del__(), called a destructor, that is invoked when the instance is about to be destroyed. This method might be used to clean up any non memory resources used by an instance.
  • 9. class Point: def __init__( self, x=0, y=0): self.x = x self.y = y def __del__(self): class_name = self.__class__.__name__ print (class_name, "destroyed") pt1 = Point() pt2 = pt1 pt3 = pt1 print (id(pt1), id(pt2), id(pt3)) # prints the ids of the obejcts del pt1 del pt2 del pt3
  • 10. Class Inheritance • Instead of starting from scratch, you can create a class by deriving it from a preexisting class by listing the parent class in parentheses after the new class name. • The child class inherits the attributes of its parent class, and you can use those attributes as if they were defined in the child class. A child class can also override data members and methods from the parent. Syntax • Derived classes are declared much like their parent class; however, a list of base classes to inherit from is given after the class name − class SubClassName (ParentClass1[, ParentClass2, ...]): 'Optional class documentation string‘
  • 11. Get And SET Attribute Get and set attribute of objects. The syntax of setattr() method is: setattr(object, name, value) setattr() Parameters The setattr() method takes three parameters • object - object whose attribute has to be set • name - string which contains the name of the attribute to be set • value - value of the attribute to be set
  • 12. class Person: name = 'Adam' p = Person() print('Before modification:', p.name) # setting name to 'John‘ setattr(p, 'name', 'John') print('After modification:', p.name) #Mainly GET and SET used for …. class Person: name = 'Adam' p = Person() # setting attribute name to None setattr(p, 'name', None) print('Name is:', p.name) # setting an attribute not present # in Person setattr(p, 'age', 23) print('Age is:', p.age)
  • 13. Get Attribute The getattr() method returns the value of the named attribute of an object. If not found, it returns the default value provided to the function. • The syntax of getattr() method is: getattr(object, name[, default]) getattr() Parameters The getattr() method takes multiple parameters: • object - object whose named attribute's value is to be returned • name - string that contains the attribute's name • default (Optional) - value that is returned when the named attribute is not found #E.G. class Person: age = 23 name = "Adam“ person = Person() # when default value is provided print('The gender is:', getattr(person, 'gender', 'Male')) # when no default value is provided print('The gender is:', getattr(person, 'gender'))
  • 14. #Inheritance Example class Parent: # define parent class parentAttr = 100 def __init__(self): print ("Calling parent constructor") def parentMethod(self): print ('Calling parent method') def setAttr(self, attr): Parent.parentAttr = attr def getAttr(self): print ("Parent attribute :", Parent.parentAttr) class Child(Parent): # define child class def __init__(self): print ("Calling child constructor") def childMethod(self): print ('Calling child method') c = Child() # instance of child c.childMethod() # child calls its method c.parentMethod() # calls parent's method c.setAttr(200) # again call parent's method c.getAttr() # again call parent's method
  • 15. Overriding Methods - You can always override your parent class methods. One reason for overriding parent's methods is because you may want special or different functionality in your subclass. • Example class Parent: # define parent class def myMethod(self): print ('Calling parent method vadil') class Child(Parent): # define child class def myMethod(self): print ('Calling child method 6okrav') c = Child() # instance of child c.myMethod() # child calls overridden method
  • 16. What is MRO ? • A class can be derived from more than one base classes in Python. This is called multiple inheritance. • In multiple inheritance, the features of all the base classes are inherited into the derived class. The syntax for multiple inheritance is similar to single inheritance. E.g.. class Super1: pass class Super2: pass class MultiDerived(Super1, Super2): pass - In the multiple inheritance scenario, any specified attribute is searched first in the current class. If not found, the search continues into parent classes in depth-first, left-right fashion without searching same class twice. - MRO Stand for Method resolution Order.
  • 17. • So, in the above example of MultiDerived class the search order is [MultiDerived, Super1, Super2, object]. This order is also called linearization of MultiDerived class and the set of rules used to find this order is called Method Resolution Order (MRO). • MRO ensures that a class always appears before its parents and in case of multiple parents, the order is same as tuple of base classes.
  • 18. Duck Typing • Duck typing is a concept that says that the “type” of the object is a matter of concern only at runtime and you don’t need to to explicitly mention the type of the object before you perform nay kind of operation on that object. • You don’t need to define the type of things like int,float etc…its called duck typing. • The following example can help in understanding this concept - • def calc(a,b): • return a+b
  • 19. Method Overloading • Same name different arguments in method that is called an method overloading. • Python doesn’t support method overloading but if we want to do then we can do as per below. ### Error def product(a, b): p = a * b print(p) def product(a, b, c): p = a * b*c print(p) #product(4, 5) product(4, 5, 5)
  • 20. It’s Work If Different Arguments as a Parameter # 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')
  • 21. Abstract Class Abstract classes: Force a class to implement methods. Abstract classes can contain abstract methods: methods without an implementation. Objects cannot be created from an abstract class. A subclass can implement an abstract class. Meaning of @ This shows that the function/method/class you're defining after a decorator is just basically passed on as an argument to the function/method immediately after the @ sign.
  • 23. import abc class AbstractAnimal(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def walk(self): ''' data ''' @abc.abstractmethod def talk(self): ''' data ''' class Duck(AbstractAnimal): name = '' def __init__(self, name): print('duck created.') self.name = name def walk(self): print('walks') def talk(self): print('quack') obj = Duck('duck1') obj.talk() obj.walk()
  • 24. Done Till Mid Your Task • Different between interface and abstract class ? My Task • Revision Of 3 Chapter • Write the question answer of 3 chapter. • IMP question of mid • Example of library program