SlideShare a Scribd company logo
OBJECT ORIENTED PROGRAMMING
OBJECT ORIENTED PROGRAMMING
IN PYTHON:
IN PYTHON:
DEFINING CLASSES
DEFINING CLASSES
IT
IT’
’S ALL OBJECTS…
S ALL OBJECTS…
 Everything in Python is really an object.
 We’ve seen hints of this already…
“hello”.upper()
list3.append(‘a’)
dict2.keys()
 New object classes can easily be defined
in addition to these built-in data-types.
 In fact, programming in Python is typically
done in an object oriented fashion.
DEFINING A CLASS
DEFINING A CLASS
 A class is a special data type which defines
how to build a certain kind of object.
 The class also stores some data items that
are shared by all the instances of this class
 Instances are objects that are created which
follow the definition given inside of the class
 Python doesn’t use separate class interface
definitions as in some languages. You just
define the class and then use it
METHODS IN CLASSES
METHODS IN CLASSES
 Define a method in a class by including
function definitions within the scope of the
class block
 There must be a special first argument
self in all of method definitions which gets
bound to the calling instance
 There is usually a special method called
__init__ in most classes
 We’ll talk about both later…
A SIMPLE CLASS DEF:
A SIMPLE CLASS DEF: STUDENT
STUDENT
class student:
“““A class representing a
student ”””
def __init__(self,n,a):
self.full_name = n
self.age = a
def get_age(self):
return self.age
CREATING AND
CREATING AND
DELETING INSTANCES
DELETING INSTANCES
INSTANTIATING OBJECTS
INSTANTIATING OBJECTS
 There is no “new” keyword as in Java.
 Just use the class name with ( ) notation and
assign the result to a variable
 __init__ serves as a constructor for the
class. Usually does some initialization work
 The arguments passed to the class name are
given to its __init__() method
 So, the __init__ method for student is passed
“Bob” and 21 and the new class instance is
bound to b:
b = student(“Bob”, 21)
CONSTRUCTOR: __INIT__
CONSTRUCTOR: __INIT__
 An __init__ method can take any number
of arguments.
 Like other functions or methods, the
arguments can be defined with default
values, making them optional to the caller.
 However, the first argument self in the
definition of __init__ is special…
SELF
SELF
 The first argument of every method is a
reference to the current instance of the class
 By convention, we name this argument
self
 In __init__, self refers to the object
currently being created; so, in other class
methods, it refers to the instance whose
method was called
SELF
SELF
 Although you must specify self explicitly
when defining the method, you don’t
include it when calling the method.
 Python passes it for you automatically
Defining a method: Calling a
method:
(this code inside a class definition.)
def set_age(self, num): >>> x.set_age(23)
self.age = num
DELETING INSTANCES: NO NEED
DELETING INSTANCES: NO NEED
TO
TO “
“FREE
FREE”
”
 When you are done with an object, you don’t
have to delete or free it explicitly.
 Python has automatic garbage collection.
 Python will automatically detect when all of
the references to a piece of memory have
gone out of scope. Automatically frees that
memory.
 There’s also no “destructor” method for
classes
ACCESS TO
ACCESS TO
ATTRIBUTES AND
ATTRIBUTES AND
METHODS
METHODS
DEFINITION OF STUDENT
DEFINITION OF STUDENT
class student:
“““A class representing a student
”””
def __init__(self,n,a):
self.full_name = n
self.age = a
def get_age(self):
return self.age
TRADITIONAL SYNTAX FOR ACCESS
TRADITIONAL SYNTAX FOR ACCESS
>>> f = student(“Bob Smith”, 23)
>>> f.full_name # Access attribute
“Bob Smith”
>>> f.get_age() # Access a method
23
ACCESSING UNKNOWN MEMBERS
ACCESSING UNKNOWN MEMBERS
 Problem: Occasionally the name of an attribute
or method of a class is only given at run time…
 Solution:
getattr(object_instance, string)
 string is a string which contains the name of an
attribute or method of a class
 getattr(object_instance, string)
returns a reference to that attribute or method
GETATTR(OBJECT_INSTANCE,
GETATTR(OBJECT_INSTANCE,
STRING)
STRING)
>>> f = student(“Bob Smith”, 23)
>>> getattr(f, “full_name”)
“Bob Smith”
>>> getattr(f, “get_age”)
<method get_age of class
studentClass at 010B3C2>
>>> getattr(f, “get_age”)() # call it
23
>>> getattr(f, “get_birthday”)
# Raises AttributeError – No method!
HASATTR(OBJECT_INSTANCE,STRIN
HASATTR(OBJECT_INSTANCE,STRIN
G)
G)
>>> f = student(“Bob Smith”, 23)
>>> hasattr(f, “full_name”)
True
>>> hasattr(f, “get_age”)
True
>>> hasattr(f, “get_birthday”)
False
ATTRIBUTES
ATTRIBUTES
TWO KINDS OF ATTRIBUTES
TWO KINDS OF ATTRIBUTES
 The non-method data stored by objects are
called attributes
 Data attributes
 Variable owned by a particular instance of a
class
 Each instance has its own value for it
 These are the most common kind of attribute
 Class attributes
 Owned by the class as a whole
 All class instances share the same value for it
 Called “static” variables in some languages
DATA ATTRIBUTES
DATA ATTRIBUTES
 Data attributes are created and initialized
by an __init__() method.
 Simply assigning to a name creates the
attribute
 Inside the class, refer to data attributes using
self
 for example, self.full_name
class teacher:
“A class representing teachers.”
def __init__(self,n):
self.full_name = n
def print_name(self):
print self.full_name
CLASS ATTRIBUTES
CLASS ATTRIBUTES
 Because all instances of a class share one copy of a
class attribute, when any instance changes it, the
value is changed for all instances
 Class attributes are defined within a class definition
and outside of any method
 Since there is one of these attributes per class and
not one per instance, they’re accessed via a different
notation:
 Access class attributes using self.__class__.name
notation -- This is just one way to do this & the safest in general.
class sample: >>> a = sample()
x = 23 >>> a.increment()
def increment(self): >>> a.__class__.x
self.__class__.x += 1 24
DATA VS. CLASS ATTRIBUTES
DATA VS. CLASS ATTRIBUTES
class counter:
overall_total = 0
# class attribute
def __init__(self):
self.my_total = 0
# data attribute
def increment(self):
counter.overall_total = 
counter.overall_total + 1
self.my_total = 
self.my_total + 1
>>> a = counter()
>>> b = counter()
>>> a.increment()
>>> b.increment()
>>> b.increment()
>>> a.my_total
1
>>> a.__class__.overall_total
3
>>> b.my_total
2
>>> b.__class__.overall_total
3
INHERITANC
INHERITANC
E
E
SUBCLASSES
SUBCLASSES
Classes can extend the definition of
other classes
 Allows use (or extension) of methods and
attributes already defined in the previous
one
To define a subclass, put the name of
the superclass in parens after the
subclass’s name on the first line of the
definition
Class Cs_student(student):
 Multiple inheritance is supported
REDEFINING METHODS
REDEFINING METHODS
 To redefine a method of the parent class,
include a new definition using the same
name in the subclass
 The old code won’t get executed
 To execute the method in the parent class in
addition to new code for some method,
explicitly call the parent’s version of method
parentClass.methodName(self,a,b,c)
 The only time you ever explicitly pass ‘self’ as
an argument is when calling a method of an
ancestor
DEFINITION OF A CLASS EXTENDING
DEFINITION OF A CLASS EXTENDING
STUDENT
STUDENT
Class Student:
“A class representing a student.”
def __init__(self,n,a):
self.full_name = n
self.age = a
def get_age(self):
return self.age
Class Cs_student (student):
“A class extending student.”
def __init__(self,n,a,s):
student.__init__(self,n,a) #Call __init__ for student
self.section_num = s
def get_age(): #Redefines get_age method entirely
print “Age: ” + str(self.age)
EXTENDING __INIT__
EXTENDING __INIT__
Same as redefining any other method…
 Commonly, the ancestor’s __init__ method
is executed in addition to new commands
 You’ll often see something like this in the
__init__ method of subclasses:
parentClass.__init__(self, x, y)
where parentClass is the name of the parent’s
class
SPECIAL BUILT-IN
SPECIAL BUILT-IN
METHODS AND ATTRIBUTES
METHODS AND ATTRIBUTES
BUILT-IN MEMBERS OF CLASSES
BUILT-IN MEMBERS OF CLASSES
Classes contain many methods and
attributes that are always included
 Most define automatic functionality
triggered by special operators or usage
of that class
 Built-in attributes define information
that must be stored for all classes.
All built-in members have double
underscores around their names:
__init__ __doc__
SPECIAL METHODS
SPECIAL METHODS
E.g., the method __repr__ exists for all
classes, and you can always redefine it
__repr__ specifies how to turn an
instance of the class into a string
 print f sometimes calls f.__repr__()
to produce a string for object f
 Typing f at the REPL prompt calls
__repr__ to determine what to display as
output
SPECIAL METHODS – EXAMPLE
SPECIAL METHODS – EXAMPLE
class student:
...
def __repr__(self):
return “I’m named ” + self.full_name
...
>>> f = student(“Bob Smith”, 23)
>>> print f
I’m named Bob Smith
>>> f
“I’m named Bob Smith”
SPECIAL METHODS
SPECIAL METHODS
 You can redefine these as well:
__init__ : The constructor for the class
__cmp__ : Define how == works for class
__len__ : Define how len( obj ) works
__copy__ : Define how to copy a class
 Other built-in methods allow you to give a
class the ability to use [ ] notation like an
array or ( ) notation like a function call
SPECIAL DATA ITEMS
SPECIAL DATA ITEMS
 These attributes exist for all classes.
__doc__ : Variable for documentation string
for class
__class__ : Variable which gives you a reference
to the class from any instance of it
__module__ : Variable which gives a reference to
the module in which the particular class is defined
__dict__ :The dictionary that is actually the
namespace for a class (but not its superclasses)
 Useful:
 dir(x) returns a list of all methods and
attributes defined for object x
SPECIAL DATA ITEMS – EXAMPLE
SPECIAL DATA ITEMS – EXAMPLE
>>> f = student(“Bob Smith”, 23)
>>> print f.__doc__
A class representing a student.
>>> f.__class__
< class studentClass at 010B4C6 >
>>> g = f.__class__(“Tom Jones”,
34)
PRIVATE DATA AND
PRIVATE DATA AND
METHODS
METHODS
 Any attribute/method with two leading
under-scores in its name (but none at the
end) is private and can’t be accessed
outside of class
 Note: Names with two underscores at the
beginning and the end are for built-in
methods or attributes for the class
 Note: There is no ‘protected’ status in
Python; so, subclasses would be unable to
access these private data either

More Related Content

Similar to Lecture on Python class -lecture123456.ppt (20)

Python unit 3 m.sc cs
Python unit 3 m.sc csPython unit 3 m.sc cs
Python unit 3 m.sc cs
KALAISELVI P
 
Python Lecture 13
Python Lecture 13Python Lecture 13
Python Lecture 13
Inzamam Baig
 
Module-5-Classes and Objects for Python Programming.pptx
Module-5-Classes and Objects for Python Programming.pptxModule-5-Classes and Objects for Python Programming.pptx
Module-5-Classes and Objects for Python Programming.pptx
YogeshKumarKJMIT
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with python
Arslan Arshad
 
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
 
Python 2. classes- cruciql for students objects1.pptx
Python 2. classes- cruciql for students objects1.pptxPython 2. classes- cruciql for students objects1.pptx
Python 2. classes- cruciql for students objects1.pptx
KiranRaj648995
 
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
Maulik Borsaniya
 
Python advance
Python advancePython advance
Python advance
Mukul Kirti Verma
 
2_Classes.pptxjdhfhdfohfshfklsfskkfsdklsdk
2_Classes.pptxjdhfhdfohfshfklsfskkfsdklsdk2_Classes.pptxjdhfhdfohfshfklsfskkfsdklsdk
2_Classes.pptxjdhfhdfohfshfklsfskkfsdklsdk
thuy27042005thieu
 
Object_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdfObject_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdf
Koteswari Kasireddy
 
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
 
Object Oriented Programming in Python.pptx
Object Oriented Programming in Python.pptxObject Oriented Programming in Python.pptx
Object Oriented Programming in Python.pptx
grpvasundhara1993
 
object oriented porgramming using Java programming
object oriented porgramming using Java programmingobject oriented porgramming using Java programming
object oriented porgramming using Java programming
afsheenfaiq2
 
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونیاسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
Mohammad Reza Kamalifard
 
OOPS-PYTHON.pptx OOPS IN PYTHON APPLIED PROGRAMMING
OOPS-PYTHON.pptx    OOPS IN PYTHON APPLIED PROGRAMMINGOOPS-PYTHON.pptx    OOPS IN PYTHON APPLIED PROGRAMMING
OOPS-PYTHON.pptx OOPS IN PYTHON APPLIED PROGRAMMING
NagarathnaRajur2
 
Python_Object_Oriented_Programming.pptx
Python_Object_Oriented_Programming.pptxPython_Object_Oriented_Programming.pptx
Python_Object_Oriented_Programming.pptx
Koteswari Kasireddy
 
Regex,functions, inheritance,class, attribute,overloding
Regex,functions, inheritance,class, attribute,overlodingRegex,functions, inheritance,class, attribute,overloding
Regex,functions, inheritance,class, attribute,overloding
sangumanikesh
 
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
 
My Object Oriented.pptx
My Object Oriented.pptxMy Object Oriented.pptx
My Object Oriented.pptx
GopalNarayan7
 
Python unit 3 m.sc cs
Python unit 3 m.sc csPython unit 3 m.sc cs
Python unit 3 m.sc cs
KALAISELVI P
 
Module-5-Classes and Objects for Python Programming.pptx
Module-5-Classes and Objects for Python Programming.pptxModule-5-Classes and Objects for Python Programming.pptx
Module-5-Classes and Objects for Python Programming.pptx
YogeshKumarKJMIT
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with python
Arslan Arshad
 
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
 
Python 2. classes- cruciql for students objects1.pptx
Python 2. classes- cruciql for students objects1.pptxPython 2. classes- cruciql for students objects1.pptx
Python 2. classes- cruciql for students objects1.pptx
KiranRaj648995
 
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
Maulik Borsaniya
 
2_Classes.pptxjdhfhdfohfshfklsfskkfsdklsdk
2_Classes.pptxjdhfhdfohfshfklsfskkfsdklsdk2_Classes.pptxjdhfhdfohfshfklsfskkfsdklsdk
2_Classes.pptxjdhfhdfohfshfklsfskkfsdklsdk
thuy27042005thieu
 
Object_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdfObject_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdf
Koteswari Kasireddy
 
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
 
Object Oriented Programming in Python.pptx
Object Oriented Programming in Python.pptxObject Oriented Programming in Python.pptx
Object Oriented Programming in Python.pptx
grpvasundhara1993
 
object oriented porgramming using Java programming
object oriented porgramming using Java programmingobject oriented porgramming using Java programming
object oriented porgramming using Java programming
afsheenfaiq2
 
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونیاسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
Mohammad Reza Kamalifard
 
OOPS-PYTHON.pptx OOPS IN PYTHON APPLIED PROGRAMMING
OOPS-PYTHON.pptx    OOPS IN PYTHON APPLIED PROGRAMMINGOOPS-PYTHON.pptx    OOPS IN PYTHON APPLIED PROGRAMMING
OOPS-PYTHON.pptx OOPS IN PYTHON APPLIED PROGRAMMING
NagarathnaRajur2
 
Python_Object_Oriented_Programming.pptx
Python_Object_Oriented_Programming.pptxPython_Object_Oriented_Programming.pptx
Python_Object_Oriented_Programming.pptx
Koteswari Kasireddy
 
Regex,functions, inheritance,class, attribute,overloding
Regex,functions, inheritance,class, attribute,overlodingRegex,functions, inheritance,class, attribute,overloding
Regex,functions, inheritance,class, attribute,overloding
sangumanikesh
 
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
 
My Object Oriented.pptx
My Object Oriented.pptxMy Object Oriented.pptx
My Object Oriented.pptx
GopalNarayan7
 

More from Reji K Dhaman (20)

lecture-1-2 modelling and simulation.pptx
lecture-1-2 modelling and simulation.pptxlecture-1-2 modelling and simulation.pptx
lecture-1-2 modelling and simulation.pptx
Reji K Dhaman
 
EE100B-p05 feedback amplifier circuits.ppt
EE100B-p05 feedback amplifier circuits.pptEE100B-p05 feedback amplifier circuits.ppt
EE100B-p05 feedback amplifier circuits.ppt
Reji K Dhaman
 
lecture-1-2 modelling and simulation.pptx
lecture-1-2 modelling and simulation.pptxlecture-1-2 modelling and simulation.pptx
lecture-1-2 modelling and simulation.pptx
Reji K Dhaman
 
EE100B-p05 feedback amplifier circuits.ppt
EE100B-p05 feedback amplifier circuits.pptEE100B-p05 feedback amplifier circuits.ppt
EE100B-p05 feedback amplifier circuits.ppt
Reji K Dhaman
 
lecture-1-2 modelling and simulation.pptx
lecture-1-2 modelling and simulation.pptxlecture-1-2 modelling and simulation.pptx
lecture-1-2 modelling and simulation.pptx
Reji K Dhaman
 
EE100B-p05 feedback Amplifier in electronics.ppt
EE100B-p05 feedback Amplifier in electronics.pptEE100B-p05 feedback Amplifier in electronics.ppt
EE100B-p05 feedback Amplifier in electronics.ppt
Reji K Dhaman
 
lecture-1-2MOdelling and Simulation.pptx
lecture-1-2MOdelling and Simulation.pptxlecture-1-2MOdelling and Simulation.pptx
lecture-1-2MOdelling and Simulation.pptx
Reji K Dhaman
 
EE100B-p05 feedback principles for electronics.ppt
EE100B-p05 feedback principles for electronics.pptEE100B-p05 feedback principles for electronics.ppt
EE100B-p05 feedback principles for electronics.ppt
Reji K Dhaman
 
Higher Secondary Thermodynamics_PPT.pptx
Higher Secondary Thermodynamics_PPT.pptxHigher Secondary Thermodynamics_PPT.pptx
Higher Secondary Thermodynamics_PPT.pptx
Reji K Dhaman
 
Atmospheric science 4 7 7 0 64580-6.pptx
Atmospheric science 4 7 7 0 64580-6.pptxAtmospheric science 4 7 7 0 64580-6.pptx
Atmospheric science 4 7 7 0 64580-6.pptx
Reji K Dhaman
 
research - types of research designs.ppt
research - types of research designs.pptresearch - types of research designs.ppt
research - types of research designs.ppt
Reji K Dhaman
 
Research Methodology Research Design-LDR 280.PPT
Research Methodology Research Design-LDR 280.PPTResearch Methodology Research Design-LDR 280.PPT
Research Methodology Research Design-LDR 280.PPT
Reji K Dhaman
 
2476442RESEARCH METHODOLOGY LECTURES.ppt
2476442RESEARCH METHODOLOGY LECTURES.ppt2476442RESEARCH METHODOLOGY LECTURES.ppt
2476442RESEARCH METHODOLOGY LECTURES.ppt
Reji K Dhaman
 
Different Types of laser Ar-ion Laser.pptx
Different Types of laser Ar-ion Laser.pptxDifferent Types of laser Ar-ion Laser.pptx
Different Types of laser Ar-ion Laser.pptx
Reji K Dhaman
 
class xi physics chapter gravitation 2.pptx
class xi physics chapter gravitation 2.pptxclass xi physics chapter gravitation 2.pptx
class xi physics chapter gravitation 2.pptx
Reji K Dhaman
 
class xi physics gravitation chapter.pptx
class xi physics gravitation chapter.pptxclass xi physics gravitation chapter.pptx
class xi physics gravitation chapter.pptx
Reji K Dhaman
 
PLUS ONE PHYSIS_GRAVITATION UNIT 1.pptx
PLUS ONE PHYSIS_GRAVITATION UNIT  1.pptxPLUS ONE PHYSIS_GRAVITATION UNIT  1.pptx
PLUS ONE PHYSIS_GRAVITATION UNIT 1.pptx
Reji K Dhaman
 
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
 
Laser Safety Training - December 2017.pptx
Laser Safety Training - December 2017.pptxLaser Safety Training - December 2017.pptx
Laser Safety Training - December 2017.pptx
Reji K Dhaman
 
LASER-concepts principle working and Theory.ppt
LASER-concepts principle working and Theory.pptLASER-concepts principle working and Theory.ppt
LASER-concepts principle working and Theory.ppt
Reji K Dhaman
 
lecture-1-2 modelling and simulation.pptx
lecture-1-2 modelling and simulation.pptxlecture-1-2 modelling and simulation.pptx
lecture-1-2 modelling and simulation.pptx
Reji K Dhaman
 
EE100B-p05 feedback amplifier circuits.ppt
EE100B-p05 feedback amplifier circuits.pptEE100B-p05 feedback amplifier circuits.ppt
EE100B-p05 feedback amplifier circuits.ppt
Reji K Dhaman
 
lecture-1-2 modelling and simulation.pptx
lecture-1-2 modelling and simulation.pptxlecture-1-2 modelling and simulation.pptx
lecture-1-2 modelling and simulation.pptx
Reji K Dhaman
 
EE100B-p05 feedback amplifier circuits.ppt
EE100B-p05 feedback amplifier circuits.pptEE100B-p05 feedback amplifier circuits.ppt
EE100B-p05 feedback amplifier circuits.ppt
Reji K Dhaman
 
lecture-1-2 modelling and simulation.pptx
lecture-1-2 modelling and simulation.pptxlecture-1-2 modelling and simulation.pptx
lecture-1-2 modelling and simulation.pptx
Reji K Dhaman
 
EE100B-p05 feedback Amplifier in electronics.ppt
EE100B-p05 feedback Amplifier in electronics.pptEE100B-p05 feedback Amplifier in electronics.ppt
EE100B-p05 feedback Amplifier in electronics.ppt
Reji K Dhaman
 
lecture-1-2MOdelling and Simulation.pptx
lecture-1-2MOdelling and Simulation.pptxlecture-1-2MOdelling and Simulation.pptx
lecture-1-2MOdelling and Simulation.pptx
Reji K Dhaman
 
EE100B-p05 feedback principles for electronics.ppt
EE100B-p05 feedback principles for electronics.pptEE100B-p05 feedback principles for electronics.ppt
EE100B-p05 feedback principles for electronics.ppt
Reji K Dhaman
 
Higher Secondary Thermodynamics_PPT.pptx
Higher Secondary Thermodynamics_PPT.pptxHigher Secondary Thermodynamics_PPT.pptx
Higher Secondary Thermodynamics_PPT.pptx
Reji K Dhaman
 
Atmospheric science 4 7 7 0 64580-6.pptx
Atmospheric science 4 7 7 0 64580-6.pptxAtmospheric science 4 7 7 0 64580-6.pptx
Atmospheric science 4 7 7 0 64580-6.pptx
Reji K Dhaman
 
research - types of research designs.ppt
research - types of research designs.pptresearch - types of research designs.ppt
research - types of research designs.ppt
Reji K Dhaman
 
Research Methodology Research Design-LDR 280.PPT
Research Methodology Research Design-LDR 280.PPTResearch Methodology Research Design-LDR 280.PPT
Research Methodology Research Design-LDR 280.PPT
Reji K Dhaman
 
2476442RESEARCH METHODOLOGY LECTURES.ppt
2476442RESEARCH METHODOLOGY LECTURES.ppt2476442RESEARCH METHODOLOGY LECTURES.ppt
2476442RESEARCH METHODOLOGY LECTURES.ppt
Reji K Dhaman
 
Different Types of laser Ar-ion Laser.pptx
Different Types of laser Ar-ion Laser.pptxDifferent Types of laser Ar-ion Laser.pptx
Different Types of laser Ar-ion Laser.pptx
Reji K Dhaman
 
class xi physics chapter gravitation 2.pptx
class xi physics chapter gravitation 2.pptxclass xi physics chapter gravitation 2.pptx
class xi physics chapter gravitation 2.pptx
Reji K Dhaman
 
class xi physics gravitation chapter.pptx
class xi physics gravitation chapter.pptxclass xi physics gravitation chapter.pptx
class xi physics gravitation chapter.pptx
Reji K Dhaman
 
PLUS ONE PHYSIS_GRAVITATION UNIT 1.pptx
PLUS ONE PHYSIS_GRAVITATION UNIT  1.pptxPLUS ONE PHYSIS_GRAVITATION UNIT  1.pptx
PLUS ONE PHYSIS_GRAVITATION UNIT 1.pptx
Reji K Dhaman
 
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
 
Laser Safety Training - December 2017.pptx
Laser Safety Training - December 2017.pptxLaser Safety Training - December 2017.pptx
Laser Safety Training - December 2017.pptx
Reji K Dhaman
 
LASER-concepts principle working and Theory.ppt
LASER-concepts principle working and Theory.pptLASER-concepts principle working and Theory.ppt
LASER-concepts principle working and Theory.ppt
Reji K Dhaman
 
Ad

Recently uploaded (20)

Search Engine Optimization (SEO) for Website Success
Search Engine Optimization (SEO) for Website SuccessSearch Engine Optimization (SEO) for Website Success
Search Engine Optimization (SEO) for Website Success
Muneeb Rana
 
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_HyderabadWebcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
 
State institute of educational technology
State institute of educational technologyState institute of educational technology
State institute of educational technology
vp5806484
 
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
Quiz Club of PSG College of Arts & Science
 
How to Create Time Off Request in Odoo 18 Time Off
How to Create Time Off Request in Odoo 18 Time OffHow to Create Time Off Request in Odoo 18 Time Off
How to Create Time Off Request in Odoo 18 Time Off
Celine George
 
How to Create a Rainbow Man Effect in Odoo 18
How to Create a Rainbow Man Effect in Odoo 18How to Create a Rainbow Man Effect in Odoo 18
How to Create a Rainbow Man Effect in Odoo 18
Celine George
 
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
Quiz Club of PSG College of Arts & Science
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
How to Create a Stage or a Pipeline in Odoo 18 CRM
How to Create a Stage or a Pipeline in Odoo 18 CRMHow to Create a Stage or a Pipeline in Odoo 18 CRM
How to Create a Stage or a Pipeline in Odoo 18 CRM
Celine George
 
Final Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptxFinal Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptx
bobby205207
 
How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18
Celine George
 
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxDiptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Arshad Shaikh
 
Nice Dream.pdf /
Nice Dream.pdf                              /Nice Dream.pdf                              /
Nice Dream.pdf /
ErinUsher3
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Smart Borrowing: Everything You Need to Know About Short Term Loans in India
Smart Borrowing: Everything You Need to Know About Short Term Loans in IndiaSmart Borrowing: Everything You Need to Know About Short Term Loans in India
Smart Borrowing: Everything You Need to Know About Short Term Loans in India
fincrifcontent
 
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Celine George
 
What are the benefits that dance brings?
What are the benefits that dance brings?What are the benefits that dance brings?
What are the benefits that dance brings?
memi27
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptxUnit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
LDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad UpdatesLDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad Updates
LDM & Mia eStudios
 
Strengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptxStrengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptx
SteffMusniQuiballo
 
Search Engine Optimization (SEO) for Website Success
Search Engine Optimization (SEO) for Website SuccessSearch Engine Optimization (SEO) for Website Success
Search Engine Optimization (SEO) for Website Success
Muneeb Rana
 
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_HyderabadWebcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
 
State institute of educational technology
State institute of educational technologyState institute of educational technology
State institute of educational technology
vp5806484
 
How to Create Time Off Request in Odoo 18 Time Off
How to Create Time Off Request in Odoo 18 Time OffHow to Create Time Off Request in Odoo 18 Time Off
How to Create Time Off Request in Odoo 18 Time Off
Celine George
 
How to Create a Rainbow Man Effect in Odoo 18
How to Create a Rainbow Man Effect in Odoo 18How to Create a Rainbow Man Effect in Odoo 18
How to Create a Rainbow Man Effect in Odoo 18
Celine George
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
How to Create a Stage or a Pipeline in Odoo 18 CRM
How to Create a Stage or a Pipeline in Odoo 18 CRMHow to Create a Stage or a Pipeline in Odoo 18 CRM
How to Create a Stage or a Pipeline in Odoo 18 CRM
Celine George
 
Final Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptxFinal Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptx
bobby205207
 
How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18How to Manage Maintenance Request in Odoo 18
How to Manage Maintenance Request in Odoo 18
Celine George
 
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxDiptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Arshad Shaikh
 
Nice Dream.pdf /
Nice Dream.pdf                              /Nice Dream.pdf                              /
Nice Dream.pdf /
ErinUsher3
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Smart Borrowing: Everything You Need to Know About Short Term Loans in India
Smart Borrowing: Everything You Need to Know About Short Term Loans in IndiaSmart Borrowing: Everything You Need to Know About Short Term Loans in India
Smart Borrowing: Everything You Need to Know About Short Term Loans in India
fincrifcontent
 
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Celine George
 
What are the benefits that dance brings?
What are the benefits that dance brings?What are the benefits that dance brings?
What are the benefits that dance brings?
memi27
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptxUnit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
LDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad UpdatesLDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad Updates
LDM & Mia eStudios
 
Strengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptxStrengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptx
SteffMusniQuiballo
 
Ad

Lecture on Python class -lecture123456.ppt

  • 1. OBJECT ORIENTED PROGRAMMING OBJECT ORIENTED PROGRAMMING IN PYTHON: IN PYTHON: DEFINING CLASSES DEFINING CLASSES
  • 2. IT IT’ ’S ALL OBJECTS… S ALL OBJECTS…  Everything in Python is really an object.  We’ve seen hints of this already… “hello”.upper() list3.append(‘a’) dict2.keys()  New object classes can easily be defined in addition to these built-in data-types.  In fact, programming in Python is typically done in an object oriented fashion.
  • 3. DEFINING A CLASS DEFINING A CLASS  A class is a special data type which defines how to build a certain kind of object.  The class also stores some data items that are shared by all the instances of this class  Instances are objects that are created which follow the definition given inside of the class  Python doesn’t use separate class interface definitions as in some languages. You just define the class and then use it
  • 4. METHODS IN CLASSES METHODS IN CLASSES  Define a method in a class by including function definitions within the scope of the class block  There must be a special first argument self in all of method definitions which gets bound to the calling instance  There is usually a special method called __init__ in most classes  We’ll talk about both later…
  • 5. A SIMPLE CLASS DEF: A SIMPLE CLASS DEF: STUDENT STUDENT class student: “““A class representing a student ””” def __init__(self,n,a): self.full_name = n self.age = a def get_age(self): return self.age
  • 6. CREATING AND CREATING AND DELETING INSTANCES DELETING INSTANCES
  • 7. INSTANTIATING OBJECTS INSTANTIATING OBJECTS  There is no “new” keyword as in Java.  Just use the class name with ( ) notation and assign the result to a variable  __init__ serves as a constructor for the class. Usually does some initialization work  The arguments passed to the class name are given to its __init__() method  So, the __init__ method for student is passed “Bob” and 21 and the new class instance is bound to b: b = student(“Bob”, 21)
  • 8. CONSTRUCTOR: __INIT__ CONSTRUCTOR: __INIT__  An __init__ method can take any number of arguments.  Like other functions or methods, the arguments can be defined with default values, making them optional to the caller.  However, the first argument self in the definition of __init__ is special…
  • 9. SELF SELF  The first argument of every method is a reference to the current instance of the class  By convention, we name this argument self  In __init__, self refers to the object currently being created; so, in other class methods, it refers to the instance whose method was called
  • 10. SELF SELF  Although you must specify self explicitly when defining the method, you don’t include it when calling the method.  Python passes it for you automatically Defining a method: Calling a method: (this code inside a class definition.) def set_age(self, num): >>> x.set_age(23) self.age = num
  • 11. DELETING INSTANCES: NO NEED DELETING INSTANCES: NO NEED TO TO “ “FREE FREE” ”  When you are done with an object, you don’t have to delete or free it explicitly.  Python has automatic garbage collection.  Python will automatically detect when all of the references to a piece of memory have gone out of scope. Automatically frees that memory.  There’s also no “destructor” method for classes
  • 12. ACCESS TO ACCESS TO ATTRIBUTES AND ATTRIBUTES AND METHODS METHODS
  • 13. DEFINITION OF STUDENT DEFINITION OF STUDENT class student: “““A class representing a student ””” def __init__(self,n,a): self.full_name = n self.age = a def get_age(self): return self.age
  • 14. TRADITIONAL SYNTAX FOR ACCESS TRADITIONAL SYNTAX FOR ACCESS >>> f = student(“Bob Smith”, 23) >>> f.full_name # Access attribute “Bob Smith” >>> f.get_age() # Access a method 23
  • 15. ACCESSING UNKNOWN MEMBERS ACCESSING UNKNOWN MEMBERS  Problem: Occasionally the name of an attribute or method of a class is only given at run time…  Solution: getattr(object_instance, string)  string is a string which contains the name of an attribute or method of a class  getattr(object_instance, string) returns a reference to that attribute or method
  • 16. GETATTR(OBJECT_INSTANCE, GETATTR(OBJECT_INSTANCE, STRING) STRING) >>> f = student(“Bob Smith”, 23) >>> getattr(f, “full_name”) “Bob Smith” >>> getattr(f, “get_age”) <method get_age of class studentClass at 010B3C2> >>> getattr(f, “get_age”)() # call it 23 >>> getattr(f, “get_birthday”) # Raises AttributeError – No method!
  • 17. HASATTR(OBJECT_INSTANCE,STRIN HASATTR(OBJECT_INSTANCE,STRIN G) G) >>> f = student(“Bob Smith”, 23) >>> hasattr(f, “full_name”) True >>> hasattr(f, “get_age”) True >>> hasattr(f, “get_birthday”) False
  • 19. TWO KINDS OF ATTRIBUTES TWO KINDS OF ATTRIBUTES  The non-method data stored by objects are called attributes  Data attributes  Variable owned by a particular instance of a class  Each instance has its own value for it  These are the most common kind of attribute  Class attributes  Owned by the class as a whole  All class instances share the same value for it  Called “static” variables in some languages
  • 20. DATA ATTRIBUTES DATA ATTRIBUTES  Data attributes are created and initialized by an __init__() method.  Simply assigning to a name creates the attribute  Inside the class, refer to data attributes using self  for example, self.full_name class teacher: “A class representing teachers.” def __init__(self,n): self.full_name = n def print_name(self): print self.full_name
  • 21. CLASS ATTRIBUTES CLASS ATTRIBUTES  Because all instances of a class share one copy of a class attribute, when any instance changes it, the value is changed for all instances  Class attributes are defined within a class definition and outside of any method  Since there is one of these attributes per class and not one per instance, they’re accessed via a different notation:  Access class attributes using self.__class__.name notation -- This is just one way to do this & the safest in general. class sample: >>> a = sample() x = 23 >>> a.increment() def increment(self): >>> a.__class__.x self.__class__.x += 1 24
  • 22. DATA VS. CLASS ATTRIBUTES DATA VS. CLASS ATTRIBUTES class counter: overall_total = 0 # class attribute def __init__(self): self.my_total = 0 # data attribute def increment(self): counter.overall_total = counter.overall_total + 1 self.my_total = self.my_total + 1 >>> a = counter() >>> b = counter() >>> a.increment() >>> b.increment() >>> b.increment() >>> a.my_total 1 >>> a.__class__.overall_total 3 >>> b.my_total 2 >>> b.__class__.overall_total 3
  • 24. SUBCLASSES SUBCLASSES Classes can extend the definition of other classes  Allows use (or extension) of methods and attributes already defined in the previous one To define a subclass, put the name of the superclass in parens after the subclass’s name on the first line of the definition Class Cs_student(student):  Multiple inheritance is supported
  • 25. REDEFINING METHODS REDEFINING METHODS  To redefine a method of the parent class, include a new definition using the same name in the subclass  The old code won’t get executed  To execute the method in the parent class in addition to new code for some method, explicitly call the parent’s version of method parentClass.methodName(self,a,b,c)  The only time you ever explicitly pass ‘self’ as an argument is when calling a method of an ancestor
  • 26. DEFINITION OF A CLASS EXTENDING DEFINITION OF A CLASS EXTENDING STUDENT STUDENT Class Student: “A class representing a student.” def __init__(self,n,a): self.full_name = n self.age = a def get_age(self): return self.age Class Cs_student (student): “A class extending student.” def __init__(self,n,a,s): student.__init__(self,n,a) #Call __init__ for student self.section_num = s def get_age(): #Redefines get_age method entirely print “Age: ” + str(self.age)
  • 27. EXTENDING __INIT__ EXTENDING __INIT__ Same as redefining any other method…  Commonly, the ancestor’s __init__ method is executed in addition to new commands  You’ll often see something like this in the __init__ method of subclasses: parentClass.__init__(self, x, y) where parentClass is the name of the parent’s class
  • 28. SPECIAL BUILT-IN SPECIAL BUILT-IN METHODS AND ATTRIBUTES METHODS AND ATTRIBUTES
  • 29. BUILT-IN MEMBERS OF CLASSES BUILT-IN MEMBERS OF CLASSES Classes contain many methods and attributes that are always included  Most define automatic functionality triggered by special operators or usage of that class  Built-in attributes define information that must be stored for all classes. All built-in members have double underscores around their names: __init__ __doc__
  • 30. SPECIAL METHODS SPECIAL METHODS E.g., the method __repr__ exists for all classes, and you can always redefine it __repr__ specifies how to turn an instance of the class into a string  print f sometimes calls f.__repr__() to produce a string for object f  Typing f at the REPL prompt calls __repr__ to determine what to display as output
  • 31. SPECIAL METHODS – EXAMPLE SPECIAL METHODS – EXAMPLE class student: ... def __repr__(self): return “I’m named ” + self.full_name ... >>> f = student(“Bob Smith”, 23) >>> print f I’m named Bob Smith >>> f “I’m named Bob Smith”
  • 32. SPECIAL METHODS SPECIAL METHODS  You can redefine these as well: __init__ : The constructor for the class __cmp__ : Define how == works for class __len__ : Define how len( obj ) works __copy__ : Define how to copy a class  Other built-in methods allow you to give a class the ability to use [ ] notation like an array or ( ) notation like a function call
  • 33. SPECIAL DATA ITEMS SPECIAL DATA ITEMS  These attributes exist for all classes. __doc__ : Variable for documentation string for class __class__ : Variable which gives you a reference to the class from any instance of it __module__ : Variable which gives a reference to the module in which the particular class is defined __dict__ :The dictionary that is actually the namespace for a class (but not its superclasses)  Useful:  dir(x) returns a list of all methods and attributes defined for object x
  • 34. SPECIAL DATA ITEMS – EXAMPLE SPECIAL DATA ITEMS – EXAMPLE >>> f = student(“Bob Smith”, 23) >>> print f.__doc__ A class representing a student. >>> f.__class__ < class studentClass at 010B4C6 > >>> g = f.__class__(“Tom Jones”, 34)
  • 35. PRIVATE DATA AND PRIVATE DATA AND METHODS METHODS  Any attribute/method with two leading under-scores in its name (but none at the end) is private and can’t be accessed outside of class  Note: Names with two underscores at the beginning and the end are for built-in methods or attributes for the class  Note: There is no ‘protected’ status in Python; so, subclasses would be unable to access these private data either