SlideShare a Scribd company logo
http://www.tutorialspoint.com/python/python_classes_objects.htm Copyright © tutorialspoint.com
PYTHON OBJECT ORIENTED
Pythonhas beenanobject-oriented language fromday one. Because of this, creating and using classes and
objects are downright easy. This chapter helps youbecome anexpert inusing Python's object-oriented
programming support.
If youdon't have any previous experience withobject-oriented (OO) programming, youmay want to consult an
introductory course onit or at least a tutorialof some sort so that youhave a grasp of the basic concepts.
However, here is smallintroductionof Object-Oriented Programming (OOP) to bring youat speed:
Overview of OOP Terminology
Class: A user-defined prototype for anobject 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 allinstances of a class. Class variables are defined withina
class but outside any of the class's methods. Class variables aren't used as frequently as instance variables
are.
Data member: A class variable or instance variable that holds data associated witha class and its
objects.
Function overloading: The assignment of more thanone behavior to a particular function. The
operationperformed varies by the types of objects (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 fromit.
Instance: Anindividualobject of a certainclass. Anobject obj that belongs to a class Circle, for
example, is aninstance of the class Circle.
Instantiation : The creationof aninstance of a class.
Method : A specialkind of functionthat is defined ina class definition.
Object : A unique instance of a data structure that's defined by its class. Anobject comprises bothdata
members (class variables and instance variables) and methods.
Operator overloading: The assignment of more thanone functionto a particular operator.
Creating Classes:
The class statement creates a new class definition. The name of the class immediately follows the keyword class
followed by a colonas follows:
class ClassName:
'Optional class documentation string'
class_suite
The class has a documentationstring, whichcanbe accessed via ClassName.__doc__.
The class_suite consists of allthe component statements defining class members, data attributes and
functions.
Example:
Following is the example of a simple Pythonclass:
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
The variable empCount is a class variable whose value would be shared among allinstances of a this class.
This canbe accessed as Employee.empCount frominside the class or outside the class.
The first method __init__() is a specialmethod, whichis called class constructor or initializationmethod
that Pythoncalls whenyoucreate a new instance of this class.
Youdeclare other class methods like normalfunctions withthe exceptionthat the first argument to each
method is self. Pythonadds the self argument to the list for you; youdon't need to include it whenyoucall
the methods.
Creating instance objects:
To create instances of a class, youcallthe class using class name and pass inwhatever arguments its __init__
method accepts.
"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
Accessing attributes:
Youaccess the object's attributes using the dot operator withobject. Class variable would be accessed using
class name as follows:
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount
Now, putting allthe concepts together:
#!/usr/bin/python
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
Whenthe above code is executed, it produces the following result:
Name : Zara ,Salary: 2000
Name : Manni ,Salary: 5000
Total Employee 2
Youcanadd, remove or modify attributes of classes and objects at any time:
emp1.age = 7 # Add an 'age' attribute.
emp1.age = 8 # Modify 'age' attribute.
del emp1.age # Delete 'age' attribute.
Instead of using the normalstatements to access attributes, youcanuse following functions:
The getattr(obj, name[, default]) : to access the attribute of object.
The hasattr(obj,name) : to check if anattribute exists or not.
The setattr(obj,name,value) : to set anattribute. If attribute does not exist, thenit would be created.
The delattr(obj, name) : to delete anattribute.
hasattr(emp1, 'age') # Returns true if 'age' attribute exists
getattr(emp1, 'age') # Returns value of 'age' attribute
setattr(emp1, 'age', 8) # Set attribute 'age' at 8
delattr(empl, 'age') # Delete attribute 'age'
Built-In Class Attributes:
Every Pythonclass keeps following built-inattributes and they canbe accessed using dot operator like any other
attribute:
__dict__ : Dictionary containing the class's namespace.
__doc__ : Class documentationstring or None if undefined.
__name__: Class name.
__module__: Module name inwhichthe class is defined. This attribute is "__main__" ininteractive
mode.
__bases__ : A possibly empty tuple containing the base classes, inthe order of their occurrence inthe
base class list.
For the above class let's try to access allthese attributes:
#!/usr/bin/python
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__
Whenthe above code is executed, it produces the following result:
Employee.__doc__: Common base class for all employees
Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: ()
Employee.__dict__: {'__module__': '__main__', 'displayCount':
<function displayCount at 0xb7c84994>, 'empCount': 2,
'displayEmployee': <function displayEmployee at 0xb7c8441c>,
'__doc__': 'Common base class for all employees',
'__init__': <function __init__ at 0xb7c846bc>}
Destroying Objects (Garbage Collection):
Pythondeletes unneeded objects (built-intypes or class instances) automatically to free memory space. The
process by whichPythonperiodically reclaims blocks of memory that no longer are inuse is termed garbage
collection.
Python's garbage collector runs during programexecutionand is triggered whenanobject's reference count
reaches zero. Anobject's reference count changes as the number of aliases that point to it changes.
Anobject's reference count increases whenit's assigned a new name or placed ina container (list, tuple or
dictionary). The object's reference count decreases whenit's deleted withdel, its reference is reassigned, or its
reference goes out of scope. Whenanobject's reference count reaches zero, Pythoncollects it automatically.
a = 40 # Create object <40>
b = a # Increase ref. count of <40>
c = [b] # Increase ref. count of <40>
del a # Decrease ref. count of <40>
b = 100 # Decrease ref. count of <40>
c[0] = -1 # Decrease ref. count of <40>
Younormally won't notice whenthe garbage collector destroys anorphaned instance and reclaims its space. But
a class canimplement the specialmethod __del__(), called a destructor, that is invoked whenthe instance is
about to be destroyed. This method might be used to cleanup any nonmemory resources used by aninstance.
Example:
This __del__() destructor prints the class name of aninstance that is about to be destroyed:
#!/usr/bin/python
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
Whenthe above code is executed, it produces following result:
3083401324 3083401324 3083401324
Point destroyed
Note: Ideally, youshould define your classes inseparate file, thenyoushould import theminyour mainprogram
file using import statement. Kindly check Python- Modules chapter for more details onimporting modules and
classes.
Class Inheritance:
Instead of starting fromscratch, youcancreate a class by deriving it froma preexisting class by listing the parent
class inparentheses after the new class name.
The child class inherits the attributes of its parent class, and youcanuse those attributes as if they were defined in
the child class. A child class canalso override data members and methods fromthe parent.
Syntax:
Derived classes are declared muchlike their parent class; however, a list of base classes to inherit fromare
givenafter the class name:
class SubClassName (ParentClass1[, ParentClass2, ...]):
'Optional class documentation string'
class_suite
Example:
#!/usr/bin/python
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
Whenthe above code is executed, it produces the following result:
Calling child constructor
Calling child method
Calling parent method
Parent attribute : 200
Similar way, youcandrive a class frommultiple parent classes as follows:
class A: # define your class A
.....
class B: # define your calss B
.....
class C(A, B): # subclass of A and B
.....
Youcanuse issubclass() or isinstance() functions to check a relationships of two classes and instances.
The issubclass(sub, sup) booleanfunctionreturns true if the givensubclass sub is indeed a subclass
of the superclass sup.
The isinstance(obj, Class) booleanfunctionreturns true if obj is aninstance of class Class or is an
instance of a subclass of Class
Overriding Methods:
Youcanalways override your parent class methods. One reasonfor overriding parent's methods is because you
may want specialor different functionality inyour subclass.
Example:
#!/usr/bin/python
class Parent: # define parent class
def myMethod(self):
print 'Calling parent method'
class Child(Parent): # define child class
def myMethod(self):
print 'Calling child method'
c = Child() # instance of child
c.myMethod() # child calls overridden method
Whenthe above code is executed, it produces the following result:
Calling child method
Base Overloading Methods:
Following table lists some generic functionality that youcanoverride inyour ownclasses:
SN Method, Description & Sample Call
1 __init__ ( self [,args...] )
Constructor (withany optionalarguments)
Sample Call: obj = className(args)
2 __del__( self )
Destructor, deletes anobject
Sample Call: dell obj
3 __repr__( self )
Evaluatable string representation
Sample Call: repr(obj)
4 __str__( self )
Printable string representation
Sample Call: str(obj)
5 __cmp__ ( self, x )
Object comparison
Sample Call: cmp(obj, x)
Overloading Operators:
Suppose you've created a Vector class to represent two-dimensionalvectors, what happens whenyouuse the
plus operator to add them? Most likely Pythonwillyellat you.
Youcould, however, define the __add__ method inyour class to performvector additionand thenthe plus
operator would behave as per expectation:
Example:
#!/usr/bin/python
class Vector:
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return 'Vector (%d, %d)' % (self.a, self.b)
def __add__(self,other):
return Vector(self.a + other.a, self.b + other.b)
v1 = Vector(2,10)
v2 = Vector(5,-2)
print v1 + v2
Whenthe above code is executed, it produces the following result:
Vector(7,8)
Data Hiding:
Anobject's attributes may or may not be visible outside the class definition. For these cases, youcanname
attributes witha double underscore prefix, and those attributes willnot be directly visible to outsiders.
Example:
#!/usr/bin/python
class JustCounter:
__secretCount = 0
def count(self):
self.__secretCount += 1
print self.__secretCount
counter = JustCounter()
counter.count()
counter.count()
print counter.__secretCount
Whenthe above code is executed, it produces the following result:
1
2
Traceback (most recent call last):
File "test.py", line 12, in <module>
print counter.__secretCount
AttributeError: JustCounter instance has no attribute '__secretCount'
Pythonprotects those members by internally changing the name to include the class name. Youcanaccess such
attributes as object._className__attrName. If youwould replace your last line as following, thenit would work
for you:
.........................
print counter._JustCounter__secretCount
Whenthe above code is executed, it produces the following result:
1
2
2
Ad

More Related Content

What's hot (20)

Spsl v unit - final
Spsl v unit - finalSpsl v unit - final
Spsl v unit - final
Sasidhar Kothuru
 
Python Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and ObjectsPython Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and Objects
P3 InfoTech Solutions Pvt. Ltd.
 
Ch8(oop)
Ch8(oop)Ch8(oop)
Ch8(oop)
Chhom Karath
 
Python oop third class
Python oop   third classPython oop   third class
Python oop third class
Aleksander Fabijan
 
Python Metaclasses
Python MetaclassesPython Metaclasses
Python Metaclasses
Nikunj Parekh
 
Python programming : Abstract classes interfaces
Python programming : Abstract classes interfacesPython programming : Abstract classes interfaces
Python programming : Abstract classes interfaces
Emertxe Information Technologies Pvt Ltd
 
Python 표준 라이브러리
Python 표준 라이브러리Python 표준 라이브러리
Python 표준 라이브러리
용 최
 
Advanced Python, Part 1
Advanced Python, Part 1Advanced Python, Part 1
Advanced Python, Part 1
Zaar Hai
 
Symfony2 and Doctrine2 Integration
Symfony2 and Doctrine2 IntegrationSymfony2 and Doctrine2 Integration
Symfony2 and Doctrine2 Integration
Jonathan Wage
 
ddd+scala
ddd+scaladdd+scala
ddd+scala
潤一 加藤
 
Building a Pluggable Plugin
Building a Pluggable PluginBuilding a Pluggable Plugin
Building a Pluggable Plugin
Brandon Dove
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHP
Lorna Mitchell
 
Doctrator Symfony Live 2011 San Francisco
Doctrator Symfony Live 2011 San FranciscoDoctrator Symfony Live 2011 San Francisco
Doctrator Symfony Live 2011 San Francisco
pablodip
 
Codeware
CodewareCodeware
Codeware
Uri Nativ
 
Python session 7 by Shan
Python session 7 by ShanPython session 7 by Shan
Python session 7 by Shan
Navaneethan Naveen
 
Python advance
Python advancePython advance
Python advance
Mukul Kirti Verma
 
Object Oriented Programming with PHP 5 - More OOP
Object Oriented Programming with PHP 5 - More OOPObject Oriented Programming with PHP 5 - More OOP
Object Oriented Programming with PHP 5 - More OOP
Wildan Maulana
 
프알못의 Keras 사용기
프알못의 Keras 사용기프알못의 Keras 사용기
프알못의 Keras 사용기
Mijeong Jeon
 
iOS와 케라스의 만남
iOS와 케라스의 만남iOS와 케라스의 만남
iOS와 케라스의 만남
Mijeong Jeon
 
Class-based views with Django
Class-based views with DjangoClass-based views with Django
Class-based views with Django
Simon Willison
 
Python Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and ObjectsPython Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and Objects
P3 InfoTech Solutions Pvt. Ltd.
 
Python 표준 라이브러리
Python 표준 라이브러리Python 표준 라이브러리
Python 표준 라이브러리
용 최
 
Advanced Python, Part 1
Advanced Python, Part 1Advanced Python, Part 1
Advanced Python, Part 1
Zaar Hai
 
Symfony2 and Doctrine2 Integration
Symfony2 and Doctrine2 IntegrationSymfony2 and Doctrine2 Integration
Symfony2 and Doctrine2 Integration
Jonathan Wage
 
Building a Pluggable Plugin
Building a Pluggable PluginBuilding a Pluggable Plugin
Building a Pluggable Plugin
Brandon Dove
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHP
Lorna Mitchell
 
Doctrator Symfony Live 2011 San Francisco
Doctrator Symfony Live 2011 San FranciscoDoctrator Symfony Live 2011 San Francisco
Doctrator Symfony Live 2011 San Francisco
pablodip
 
Object Oriented Programming with PHP 5 - More OOP
Object Oriented Programming with PHP 5 - More OOPObject Oriented Programming with PHP 5 - More OOP
Object Oriented Programming with PHP 5 - More OOP
Wildan Maulana
 
프알못의 Keras 사용기
프알못의 Keras 사용기프알못의 Keras 사용기
프알못의 Keras 사용기
Mijeong Jeon
 
iOS와 케라스의 만남
iOS와 케라스의 만남iOS와 케라스의 만남
iOS와 케라스의 만남
Mijeong Jeon
 
Class-based views with Django
Class-based views with DjangoClass-based views with Django
Class-based views with Django
Simon Willison
 

Similar to Python classes objects (20)

Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 
Spsl vi unit final
Spsl vi unit finalSpsl vi unit final
Spsl vi unit final
Sasidhar Kothuru
 
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHONUNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
drkangurajuphd
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Three
amiable_indian
 
Unit - 3.pptx
Unit - 3.pptxUnit - 3.pptx
Unit - 3.pptx
Kongunadu College of Engineering and Technology
 
Lesson on Python Classes by Matt Wufus 2003
Lesson on Python Classes by Matt Wufus 2003Lesson on Python Classes by Matt Wufus 2003
Lesson on Python Classes by Matt Wufus 2003
davidlin271898
 
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptxPYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
mru761077
 
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
 
Pythonclass
PythonclassPythonclass
Pythonclass
baabtra.com - No. 1 supplier of quality freshers
 
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
 
Programming Primer EncapsulationVB
Programming Primer EncapsulationVBProgramming Primer EncapsulationVB
Programming Primer EncapsulationVB
sunmitraeducation
 
Object Oriented Programming in Python.pptx
Object Oriented Programming in Python.pptxObject Oriented Programming in Python.pptx
Object Oriented Programming in Python.pptx
grpvasundhara1993
 
Python_Unit_2 OOPS.pptx
Python_Unit_2  OOPS.pptxPython_Unit_2  OOPS.pptx
Python_Unit_2 OOPS.pptx
ChhaviCoachingCenter
 
My Object Oriented.pptx
My Object Oriented.pptxMy Object Oriented.pptx
My Object Oriented.pptx
GopalNarayan7
 
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 with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with python
Arslan Arshad
 
UNIT-5 object oriented programming lecture
UNIT-5 object oriented programming lectureUNIT-5 object oriented programming lecture
UNIT-5 object oriented programming lecture
w6vsy4fmpy
 
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
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHONUNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
drkangurajuphd
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Three
amiable_indian
 
Lesson on Python Classes by Matt Wufus 2003
Lesson on Python Classes by Matt Wufus 2003Lesson on Python Classes by Matt Wufus 2003
Lesson on Python Classes by Matt Wufus 2003
davidlin271898
 
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptxPYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
mru761077
 
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
 
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
 
Programming Primer EncapsulationVB
Programming Primer EncapsulationVBProgramming Primer EncapsulationVB
Programming Primer EncapsulationVB
sunmitraeducation
 
Object Oriented Programming in Python.pptx
Object Oriented Programming in Python.pptxObject Oriented Programming in Python.pptx
Object Oriented Programming in Python.pptx
grpvasundhara1993
 
My Object Oriented.pptx
My Object Oriented.pptxMy Object Oriented.pptx
My Object Oriented.pptx
GopalNarayan7
 
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 with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with python
Arslan Arshad
 
UNIT-5 object oriented programming lecture
UNIT-5 object oriented programming lectureUNIT-5 object oriented programming lecture
UNIT-5 object oriented programming lecture
w6vsy4fmpy
 
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
 
Ad

More from Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai (20)

PWM Arduino Experiment for Engineering pra
PWM Arduino Experiment for Engineering praPWM Arduino Experiment for Engineering pra
PWM Arduino Experiment for Engineering pra
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Artificial Intelligence (AI) application in Agriculture Area
Artificial Intelligence (AI) application in Agriculture Area Artificial Intelligence (AI) application in Agriculture Area
Artificial Intelligence (AI) application in Agriculture Area
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
VLSI Design Book CMOS_Circuit_Design__Layout__and_Simulation
VLSI Design Book CMOS_Circuit_Design__Layout__and_SimulationVLSI Design Book CMOS_Circuit_Design__Layout__and_Simulation
VLSI Design Book CMOS_Circuit_Design__Layout__and_Simulation
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Question Bank: Network Management in Telecommunication
Question Bank: Network Management in TelecommunicationQuestion Bank: Network Management in Telecommunication
Question Bank: Network Management in Telecommunication
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
INTRODUCTION TO CYBER LAW The Concept of Cyberspace Cyber law Cyber crime.pdf
INTRODUCTION TO CYBER LAW The Concept of Cyberspace Cyber law Cyber crime.pdfINTRODUCTION TO CYBER LAW The Concept of Cyberspace Cyber law Cyber crime.pdf
INTRODUCTION TO CYBER LAW The Concept of Cyberspace Cyber law Cyber crime.pdf
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
LRU_Replacement-Policy.pdf
LRU_Replacement-Policy.pdfLRU_Replacement-Policy.pdf
LRU_Replacement-Policy.pdf
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Network Management Principles and Practice - 2nd Edition (2010)_2.pdf
Network Management Principles and Practice - 2nd Edition (2010)_2.pdfNetwork Management Principles and Practice - 2nd Edition (2010)_2.pdf
Network Management Principles and Practice - 2nd Edition (2010)_2.pdf
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Euler Method Details
Euler Method Details Euler Method Details
Euler Method Details
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Mini Project fo BE Engineering students
Mini Project fo BE Engineering  students  Mini Project fo BE Engineering  students
Mini Project fo BE Engineering students
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Mini Project for Engineering Students BE or Btech Engineering students
Mini Project for Engineering Students BE or Btech Engineering students Mini Project for Engineering Students BE or Btech Engineering students
Mini Project for Engineering Students BE or Btech Engineering students
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Ballistics Detsils
Ballistics Detsils Ballistics Detsils
Ballistics Detsils
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
VLSI Design_LAB MANUAL By Umakant Gohatre
VLSI Design_LAB MANUAL By Umakant GohatreVLSI Design_LAB MANUAL By Umakant Gohatre
VLSI Design_LAB MANUAL By Umakant Gohatre
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Cryptography and Network Security
Cryptography and Network SecurityCryptography and Network Security
Cryptography and Network Security
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
cyber crime, Cyber Security, Introduction, Umakant Bhaskar Gohatre
cyber crime, Cyber Security, Introduction, Umakant Bhaskar Gohatre cyber crime, Cyber Security, Introduction, Umakant Bhaskar Gohatre
cyber crime, Cyber Security, Introduction, Umakant Bhaskar Gohatre
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Image Compression, Introduction Data Compression/ Data compression, modelling...
Image Compression, Introduction Data Compression/ Data compression, modelling...Image Compression, Introduction Data Compression/ Data compression, modelling...
Image Compression, Introduction Data Compression/ Data compression, modelling...
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Introduction Data Compression/ Data compression, modelling and coding,Image C...
Introduction Data Compression/ Data compression, modelling and coding,Image C...Introduction Data Compression/ Data compression, modelling and coding,Image C...
Introduction Data Compression/ Data compression, modelling and coding,Image C...
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Python overview
Python overviewPython overview
Python overview
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Python numbers
Python numbersPython numbers
Python numbers
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Python networking
Python networkingPython networking
Python networking
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Python multithreading
Python multithreadingPython multithreading
Python multithreading
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Ad

Recently uploaded (20)

最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
Taqyea
 
Introduction to FLUID MECHANICS & KINEMATICS
Introduction to FLUID MECHANICS &  KINEMATICSIntroduction to FLUID MECHANICS &  KINEMATICS
Introduction to FLUID MECHANICS & KINEMATICS
narayanaswamygdas
 
Compiler Design_Code Optimization tech.pptx
Compiler Design_Code Optimization tech.pptxCompiler Design_Code Optimization tech.pptx
Compiler Design_Code Optimization tech.pptx
RushaliDeshmukh2
 
Nanometer Metal-Organic-Framework Literature Comparison
Nanometer Metal-Organic-Framework  Literature ComparisonNanometer Metal-Organic-Framework  Literature Comparison
Nanometer Metal-Organic-Framework Literature Comparison
Chris Harding
 
Routing Riverdale - A New Bus Connection
Routing Riverdale - A New Bus ConnectionRouting Riverdale - A New Bus Connection
Routing Riverdale - A New Bus Connection
jzb7232
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
Main cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxb
Main cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxbMain cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxb
Main cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxb
SunilSingh610661
 
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjjseninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
AjijahamadKhaji
 
Compiler Design_Syntax Directed Translation.pptx
Compiler Design_Syntax Directed Translation.pptxCompiler Design_Syntax Directed Translation.pptx
Compiler Design_Syntax Directed Translation.pptx
RushaliDeshmukh2
 
COMPUTER GRAPHICS AND VISUALIZATION :MODULE-02 notes [BCG402-CG&V].pdf
COMPUTER GRAPHICS AND VISUALIZATION :MODULE-02 notes [BCG402-CG&V].pdfCOMPUTER GRAPHICS AND VISUALIZATION :MODULE-02 notes [BCG402-CG&V].pdf
COMPUTER GRAPHICS AND VISUALIZATION :MODULE-02 notes [BCG402-CG&V].pdf
Alvas Institute of Engineering and technology, Moodabidri
 
COMPUTER GRAPHICS AND VISUALIZATION :MODULE-1 notes [BCG402-CG&V].pdf
COMPUTER GRAPHICS AND VISUALIZATION :MODULE-1 notes [BCG402-CG&V].pdfCOMPUTER GRAPHICS AND VISUALIZATION :MODULE-1 notes [BCG402-CG&V].pdf
COMPUTER GRAPHICS AND VISUALIZATION :MODULE-1 notes [BCG402-CG&V].pdf
Alvas Institute of Engineering and technology, Moodabidri
 
Dynamics of Structures with Uncertain Properties.pptx
Dynamics of Structures with Uncertain Properties.pptxDynamics of Structures with Uncertain Properties.pptx
Dynamics of Structures with Uncertain Properties.pptx
University of Glasgow
 
NOMA analysis in 5G communication systems
NOMA analysis in 5G communication systemsNOMA analysis in 5G communication systems
NOMA analysis in 5G communication systems
waleedali330654
 
SICPA: Fabien Keller - background introduction
SICPA: Fabien Keller - background introductionSICPA: Fabien Keller - background introduction
SICPA: Fabien Keller - background introduction
fabienklr
 
Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...
Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...
Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...
Journal of Soft Computing in Civil Engineering
 
Analog electronic circuits with some imp
Analog electronic circuits with some impAnalog electronic circuits with some imp
Analog electronic circuits with some imp
KarthikTG7
 
2025 Apply BTech CEC .docx
2025 Apply BTech CEC                 .docx2025 Apply BTech CEC                 .docx
2025 Apply BTech CEC .docx
tusharmanagementquot
 
Evonik Overview Visiomer Specialty Methacrylates.pdf
Evonik Overview Visiomer Specialty Methacrylates.pdfEvonik Overview Visiomer Specialty Methacrylates.pdf
Evonik Overview Visiomer Specialty Methacrylates.pdf
szhang13
 
Reese McCrary_ The Role of Perseverance in Engineering Success.pdf
Reese McCrary_ The Role of Perseverance in Engineering Success.pdfReese McCrary_ The Role of Perseverance in Engineering Success.pdf
Reese McCrary_ The Role of Perseverance in Engineering Success.pdf
Reese McCrary
 
Novel Plug Flow Reactor with Recycle For Growth Control
Novel Plug Flow Reactor with Recycle For Growth ControlNovel Plug Flow Reactor with Recycle For Growth Control
Novel Plug Flow Reactor with Recycle For Growth Control
Chris Harding
 
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
Taqyea
 
Introduction to FLUID MECHANICS & KINEMATICS
Introduction to FLUID MECHANICS &  KINEMATICSIntroduction to FLUID MECHANICS &  KINEMATICS
Introduction to FLUID MECHANICS & KINEMATICS
narayanaswamygdas
 
Compiler Design_Code Optimization tech.pptx
Compiler Design_Code Optimization tech.pptxCompiler Design_Code Optimization tech.pptx
Compiler Design_Code Optimization tech.pptx
RushaliDeshmukh2
 
Nanometer Metal-Organic-Framework Literature Comparison
Nanometer Metal-Organic-Framework  Literature ComparisonNanometer Metal-Organic-Framework  Literature Comparison
Nanometer Metal-Organic-Framework Literature Comparison
Chris Harding
 
Routing Riverdale - A New Bus Connection
Routing Riverdale - A New Bus ConnectionRouting Riverdale - A New Bus Connection
Routing Riverdale - A New Bus Connection
jzb7232
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
Main cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxb
Main cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxbMain cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxb
Main cotrol jdbjbdcnxbjbjzjjjcjicbjxbcjcxbjcxb
SunilSingh610661
 
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjjseninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
AjijahamadKhaji
 
Compiler Design_Syntax Directed Translation.pptx
Compiler Design_Syntax Directed Translation.pptxCompiler Design_Syntax Directed Translation.pptx
Compiler Design_Syntax Directed Translation.pptx
RushaliDeshmukh2
 
Dynamics of Structures with Uncertain Properties.pptx
Dynamics of Structures with Uncertain Properties.pptxDynamics of Structures with Uncertain Properties.pptx
Dynamics of Structures with Uncertain Properties.pptx
University of Glasgow
 
NOMA analysis in 5G communication systems
NOMA analysis in 5G communication systemsNOMA analysis in 5G communication systems
NOMA analysis in 5G communication systems
waleedali330654
 
SICPA: Fabien Keller - background introduction
SICPA: Fabien Keller - background introductionSICPA: Fabien Keller - background introduction
SICPA: Fabien Keller - background introduction
fabienklr
 
Analog electronic circuits with some imp
Analog electronic circuits with some impAnalog electronic circuits with some imp
Analog electronic circuits with some imp
KarthikTG7
 
Evonik Overview Visiomer Specialty Methacrylates.pdf
Evonik Overview Visiomer Specialty Methacrylates.pdfEvonik Overview Visiomer Specialty Methacrylates.pdf
Evonik Overview Visiomer Specialty Methacrylates.pdf
szhang13
 
Reese McCrary_ The Role of Perseverance in Engineering Success.pdf
Reese McCrary_ The Role of Perseverance in Engineering Success.pdfReese McCrary_ The Role of Perseverance in Engineering Success.pdf
Reese McCrary_ The Role of Perseverance in Engineering Success.pdf
Reese McCrary
 
Novel Plug Flow Reactor with Recycle For Growth Control
Novel Plug Flow Reactor with Recycle For Growth ControlNovel Plug Flow Reactor with Recycle For Growth Control
Novel Plug Flow Reactor with Recycle For Growth Control
Chris Harding
 

Python classes objects

  • 1. http://www.tutorialspoint.com/python/python_classes_objects.htm Copyright © tutorialspoint.com PYTHON OBJECT ORIENTED Pythonhas beenanobject-oriented language fromday one. Because of this, creating and using classes and objects are downright easy. This chapter helps youbecome anexpert inusing Python's object-oriented programming support. If youdon't have any previous experience withobject-oriented (OO) programming, youmay want to consult an introductory course onit or at least a tutorialof some sort so that youhave a grasp of the basic concepts. However, here is smallintroductionof Object-Oriented Programming (OOP) to bring youat speed: Overview of OOP Terminology Class: A user-defined prototype for anobject 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 allinstances of a class. Class variables are defined withina class but outside any of the class's methods. Class variables aren't used as frequently as instance variables are. Data member: A class variable or instance variable that holds data associated witha class and its objects. Function overloading: The assignment of more thanone behavior to a particular function. The operationperformed varies by the types of objects (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 fromit. Instance: Anindividualobject of a certainclass. Anobject obj that belongs to a class Circle, for example, is aninstance of the class Circle. Instantiation : The creationof aninstance of a class. Method : A specialkind of functionthat is defined ina class definition. Object : A unique instance of a data structure that's defined by its class. Anobject comprises bothdata members (class variables and instance variables) and methods. Operator overloading: The assignment of more thanone functionto a particular operator. Creating Classes: The class statement creates a new class definition. The name of the class immediately follows the keyword class followed by a colonas follows: class ClassName: 'Optional class documentation string' class_suite The class has a documentationstring, whichcanbe accessed via ClassName.__doc__. The class_suite consists of allthe component statements defining class members, data attributes and functions. Example: Following is the example of a simple Pythonclass:
  • 2. 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 The variable empCount is a class variable whose value would be shared among allinstances of a this class. This canbe accessed as Employee.empCount frominside the class or outside the class. The first method __init__() is a specialmethod, whichis called class constructor or initializationmethod that Pythoncalls whenyoucreate a new instance of this class. Youdeclare other class methods like normalfunctions withthe exceptionthat the first argument to each method is self. Pythonadds the self argument to the list for you; youdon't need to include it whenyoucall the methods. Creating instance objects: To create instances of a class, youcallthe class using class name and pass inwhatever arguments its __init__ method accepts. "This would create first object of Employee class" emp1 = Employee("Zara", 2000) "This would create second object of Employee class" emp2 = Employee("Manni", 5000) Accessing attributes: Youaccess the object's attributes using the dot operator withobject. Class variable would be accessed using class name as follows: emp1.displayEmployee() emp2.displayEmployee() print "Total Employee %d" % Employee.empCount Now, putting allthe concepts together: #!/usr/bin/python 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)
  • 3. emp1.displayEmployee() emp2.displayEmployee() print "Total Employee %d" % Employee.empCount Whenthe above code is executed, it produces the following result: Name : Zara ,Salary: 2000 Name : Manni ,Salary: 5000 Total Employee 2 Youcanadd, remove or modify attributes of classes and objects at any time: emp1.age = 7 # Add an 'age' attribute. emp1.age = 8 # Modify 'age' attribute. del emp1.age # Delete 'age' attribute. Instead of using the normalstatements to access attributes, youcanuse following functions: The getattr(obj, name[, default]) : to access the attribute of object. The hasattr(obj,name) : to check if anattribute exists or not. The setattr(obj,name,value) : to set anattribute. If attribute does not exist, thenit would be created. The delattr(obj, name) : to delete anattribute. hasattr(emp1, 'age') # Returns true if 'age' attribute exists getattr(emp1, 'age') # Returns value of 'age' attribute setattr(emp1, 'age', 8) # Set attribute 'age' at 8 delattr(empl, 'age') # Delete attribute 'age' Built-In Class Attributes: Every Pythonclass keeps following built-inattributes and they canbe accessed using dot operator like any other attribute: __dict__ : Dictionary containing the class's namespace. __doc__ : Class documentationstring or None if undefined. __name__: Class name. __module__: Module name inwhichthe class is defined. This attribute is "__main__" ininteractive mode. __bases__ : A possibly empty tuple containing the base classes, inthe order of their occurrence inthe base class list. For the above class let's try to access allthese attributes: #!/usr/bin/python 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
  • 4. 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__ Whenthe above code is executed, it produces the following result: Employee.__doc__: Common base class for all employees Employee.__name__: Employee Employee.__module__: __main__ Employee.__bases__: () Employee.__dict__: {'__module__': '__main__', 'displayCount': <function displayCount at 0xb7c84994>, 'empCount': 2, 'displayEmployee': <function displayEmployee at 0xb7c8441c>, '__doc__': 'Common base class for all employees', '__init__': <function __init__ at 0xb7c846bc>} Destroying Objects (Garbage Collection): Pythondeletes unneeded objects (built-intypes or class instances) automatically to free memory space. The process by whichPythonperiodically reclaims blocks of memory that no longer are inuse is termed garbage collection. Python's garbage collector runs during programexecutionand is triggered whenanobject's reference count reaches zero. Anobject's reference count changes as the number of aliases that point to it changes. Anobject's reference count increases whenit's assigned a new name or placed ina container (list, tuple or dictionary). The object's reference count decreases whenit's deleted withdel, its reference is reassigned, or its reference goes out of scope. Whenanobject's reference count reaches zero, Pythoncollects it automatically. a = 40 # Create object <40> b = a # Increase ref. count of <40> c = [b] # Increase ref. count of <40> del a # Decrease ref. count of <40> b = 100 # Decrease ref. count of <40> c[0] = -1 # Decrease ref. count of <40> Younormally won't notice whenthe garbage collector destroys anorphaned instance and reclaims its space. But a class canimplement the specialmethod __del__(), called a destructor, that is invoked whenthe instance is about to be destroyed. This method might be used to cleanup any nonmemory resources used by aninstance. Example: This __del__() destructor prints the class name of aninstance that is about to be destroyed: #!/usr/bin/python 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 Whenthe above code is executed, it produces following result:
  • 5. 3083401324 3083401324 3083401324 Point destroyed Note: Ideally, youshould define your classes inseparate file, thenyoushould import theminyour mainprogram file using import statement. Kindly check Python- Modules chapter for more details onimporting modules and classes. Class Inheritance: Instead of starting fromscratch, youcancreate a class by deriving it froma preexisting class by listing the parent class inparentheses after the new class name. The child class inherits the attributes of its parent class, and youcanuse those attributes as if they were defined in the child class. A child class canalso override data members and methods fromthe parent. Syntax: Derived classes are declared muchlike their parent class; however, a list of base classes to inherit fromare givenafter the class name: class SubClassName (ParentClass1[, ParentClass2, ...]): 'Optional class documentation string' class_suite Example: #!/usr/bin/python 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 Whenthe above code is executed, it produces the following result: Calling child constructor Calling child method Calling parent method Parent attribute : 200 Similar way, youcandrive a class frommultiple parent classes as follows: class A: # define your class A .....
  • 6. class B: # define your calss B ..... class C(A, B): # subclass of A and B ..... Youcanuse issubclass() or isinstance() functions to check a relationships of two classes and instances. The issubclass(sub, sup) booleanfunctionreturns true if the givensubclass sub is indeed a subclass of the superclass sup. The isinstance(obj, Class) booleanfunctionreturns true if obj is aninstance of class Class or is an instance of a subclass of Class Overriding Methods: Youcanalways override your parent class methods. One reasonfor overriding parent's methods is because you may want specialor different functionality inyour subclass. Example: #!/usr/bin/python class Parent: # define parent class def myMethod(self): print 'Calling parent method' class Child(Parent): # define child class def myMethod(self): print 'Calling child method' c = Child() # instance of child c.myMethod() # child calls overridden method Whenthe above code is executed, it produces the following result: Calling child method Base Overloading Methods: Following table lists some generic functionality that youcanoverride inyour ownclasses: SN Method, Description & Sample Call 1 __init__ ( self [,args...] ) Constructor (withany optionalarguments) Sample Call: obj = className(args) 2 __del__( self ) Destructor, deletes anobject Sample Call: dell obj 3 __repr__( self ) Evaluatable string representation Sample Call: repr(obj) 4 __str__( self ) Printable string representation Sample Call: str(obj) 5 __cmp__ ( self, x ) Object comparison Sample Call: cmp(obj, x)
  • 7. Overloading Operators: Suppose you've created a Vector class to represent two-dimensionalvectors, what happens whenyouuse the plus operator to add them? Most likely Pythonwillyellat you. Youcould, however, define the __add__ method inyour class to performvector additionand thenthe plus operator would behave as per expectation: Example: #!/usr/bin/python class Vector: def __init__(self, a, b): self.a = a self.b = b def __str__(self): return 'Vector (%d, %d)' % (self.a, self.b) def __add__(self,other): return Vector(self.a + other.a, self.b + other.b) v1 = Vector(2,10) v2 = Vector(5,-2) print v1 + v2 Whenthe above code is executed, it produces the following result: Vector(7,8) Data Hiding: Anobject's attributes may or may not be visible outside the class definition. For these cases, youcanname attributes witha double underscore prefix, and those attributes willnot be directly visible to outsiders. Example: #!/usr/bin/python class JustCounter: __secretCount = 0 def count(self): self.__secretCount += 1 print self.__secretCount counter = JustCounter() counter.count() counter.count() print counter.__secretCount Whenthe above code is executed, it produces the following result: 1 2 Traceback (most recent call last): File "test.py", line 12, in <module> print counter.__secretCount AttributeError: JustCounter instance has no attribute '__secretCount' Pythonprotects those members by internally changing the name to include the class name. Youcanaccess such attributes as object._className__attrName. If youwould replace your last line as following, thenit would work
  • 8. for you: ......................... print counter._JustCounter__secretCount Whenthe above code is executed, it produces the following result: 1 2 2