SlideShare une entreprise Scribd logo
1  sur  27
http://www.skillbrew.com
/Skillbrew
Talent brewed by the
industry itself
Classes and Objects
Pavan Verma
@YinYangPavan
Founder, P3 InfoTech Solutions Pvt. Ltd.
1
Python Programming Essentials
© SkillBrew http://skillbrew.com
Contents
 Defining a class
 Class attributes
 Class methods
 Class instances
 __init__ method
 self keyword
 Accessing attributes and methods
 Deleting attributes
 Types of attributes
 Inheritance
 Method overriding
 Calling parent functions
2
© SkillBrew http://skillbrew.com
Defining a class
A class is a special data type which defines how
to build a certain kind of object
class className():
# statements
Use the class keyword to define a class
3
© SkillBrew http://skillbrew.com
Defining a class
class Calculator():
counter = 0
def __init__(self):
pass
def add(self):
pass
class keyword to
define a class
A class definition creates a class object from which
class instances may be created
4
© SkillBrew http://skillbrew.com
Class Attributes
class Calculator():
counter = 0
def __init__(self):
pass
def add(self):
pass
class attributes are
just like variables
5
© SkillBrew http://skillbrew.com
Class Methods
class Calculator():
counter = 0
def __init__(self):
pass
def add(self):
pass
class methods are
functions invoked on an
instance of the class
6
© SkillBrew http://skillbrew.com
Class Instances
calc = Calculator()
• In order to you use it we create an instance of
class
• Instances are objects created that use the class
definition
Just call the class definition like a function to create
a class instance
7
© SkillBrew http://skillbrew.com
__init__ method
• __init__ method is like an initialization
constructor
• When a class defines an __init__ ()
method, class instantiation automatically invokes
__init__() method for the newly created
class instance
8
© SkillBrew http://skillbrew.com
__init__ method (2)
class Calculator():
counter = 0
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def add(self):
pass
calc = Calculator(10, 20)
print calc.x
print calc.y
Output:
10
20
9
© SkillBrew http://skillbrew.com
self keyword
• 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
• In other class methods, it refers to the instance
whose method was called
• Similar to the keyword this in Java or C++
10
© SkillBrew http://skillbrew.com
Accessing attributes and methods
Use the dot operator to access class attributes and
methods
calc = Calculator(10, 20)
print calc.x
print calc.y
print calc.counter
Output:
10
20
0
11
© SkillBrew http://skillbrew.com
Accessing attributes and methods (2)
class Calculator():
counter = 0
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def add(self):
return self.x + self.y
calc = Calculator(10, 20)
print calc.add()
• 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
12
© SkillBrew http://skillbrew.com
Deleting Instances
• 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 references
to a piece of memory have gone out of scope.
Automatically frees the memory.
• Garbage collection works well, hence fewer memory
leaks
• There’s also no “destructor” method for classes.
13
© SkillBrew http://skillbrew.com
Attributes
14
© SkillBrew http://skillbrew.com
Two kinds of Attributes
1. class attributes
2. data attributes
15
© SkillBrew http://skillbrew.com
Data attributes
class Calculator():
counter = 0
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def add(self):
return self.x + self.y
calc = Calculator(10, 20)
print calc.x # 10
print calc.y # 20
calc2 = Calculator(15, 35)
print calc2.x # 15
print calc2.y # 35
• Data attributes are
variables owned by a
particular instance
• Each instance has its own
value for data attributes
16
© SkillBrew http://skillbrew.com
Data attributes (2)
class Calculator():
counter = 0
def __init__(self, x=0, y=0):
self.x = x
self.y = y
calc = Calculator(10, 20)
calc.z = calc.x + calc.y
print calc.z
print calc.__dict__
Output:
30
{'y': 20, 'x': 10, 'z': 30}
17
• In Python classes you don’t
have a restriction of
declaring all data
attributes before hand,
you can create data
attributes at runtime
anywhere
• calc.z is an attribute
which is defined at
runtime outside the class
definition
© SkillBrew http://skillbrew.com
Class attributes
class Calculator():
counter = 0
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def add(self):
self.__class__.counter += 1
return self.x + self.y
calc = Calculator(10, 20)
print calc.add()
print calc.counter # 1
calc2 = Calculator(30, 40)
print calc2.add()
print calc2.counter # 2
• Access the class
attribute using
self.__class__.count
er
• Class attributes are
shared among all
instances
18
© SkillBrew http://skillbrew.com
Class attributes (2)
 Class attributes are defined within a class definition
and outside of any method
 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
self.__class__.attribute_name
19
© SkillBrew http://skillbrew.com
Data attributes
 Variable owned by a
particular instance
 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
 Good for
• Class-wide constants
• Building counter of how
many instances of the
class have been made
Data attributes vs Class attributes
20
© SkillBrew http://skillbrew.com
Inheritance
21
© SkillBrew http://skillbrew.com
Inheritance
class Shape(object):
def name(self, shape):
print "Shape: %s" % shape
class Square(Shape):
def area(self, side):
return side**2
Shape is the
parent class
Square is the
child class inherits
Shape
class Parent(object):
pass
class Child(Parent):
pass
22
© SkillBrew http://skillbrew.com
Inheritance (2)
class Shape(object):
def name(self, shape):
print "Shape: %s" % shape
class Square(Shape):
def area(self, side):
return side**2
s = Square()
s.name("square")
print s.area(2)
Output:
Shape: square
4
Child class Square has access to
Parent classes methods and
attributes
23
© SkillBrew http://skillbrew.com
Method overriding
class Shape(object):
def name(self, shape):
print "Shape: %s" % shape
class Square(Shape):
def name(self, shape):
print "Child class Shape %s" % shape
def area(self, side):
return side**2
s = Square()
s.name("square")
print s.area(2)
Output:
Child class Shape square
4
24
© SkillBrew http://skillbrew.com
Calling the parent method
class Shape(object):
def name(self, shape):
print "Shape: %s" % shape
class Square(Shape):
def name(self, shape):
super(Square, self).name(shape)
print "Child class Shape %s" % shape
def area(self, side):
return side**2
s = Square()
s.name("square")
Use super keyword to call parent class method
super(ChildClass, self).method(args)
25
© SkillBrew http://skillbrew.com
Class & Static Methods
class Calculator(object):
counter = 0
def __init__(self, x=0, y=0):
...
def add(self):
...
@classmethod
def update_counter(cls):
cls.counter += 1
@staticmethod
def show_help():
print 'This calculator can
add'
26
© SkillBrew http://skillbrew.com
Resources
 http://www.diveintopython.net/object_o
riented_framework/defining_classes.html
 http://docs.python.org/2/tutorial/classes
.html
 http://docs.python.org/2/library/function
s.html#super
27

Contenu connexe

Tendances

Binary Search - Design & Analysis of Algorithms
Binary Search - Design & Analysis of AlgorithmsBinary Search - Design & Analysis of Algorithms
Binary Search - Design & Analysis of AlgorithmsDrishti Bhalla
 
SEARCHING AND SORTING ALGORITHMS
SEARCHING AND SORTING ALGORITHMSSEARCHING AND SORTING ALGORITHMS
SEARCHING AND SORTING ALGORITHMSGokul Hari
 
Queue in Data Structure
Queue in Data Structure Queue in Data Structure
Queue in Data Structure Janki Shah
 
Python – Object Oriented Programming
Python – Object Oriented Programming Python – Object Oriented Programming
Python – Object Oriented Programming Raghunath A
 
Deque and its applications
Deque and its applicationsDeque and its applications
Deque and its applicationsJsaddam Hussain
 
Queue data structure
Queue data structureQueue data structure
Queue data structureanooppjoseph
 
Introduction to Recursion (Python)
Introduction to Recursion (Python)Introduction to Recursion (Python)
Introduction to Recursion (Python)Thai Pangsakulyanont
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methodsShubham Dwivedi
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search TreeAbhishek L.R
 
THREADED BINARY TREE AND BINARY SEARCH TREE
THREADED BINARY TREE AND BINARY SEARCH TREETHREADED BINARY TREE AND BINARY SEARCH TREE
THREADED BINARY TREE AND BINARY SEARCH TREESiddhi Shrivas
 

Tendances (20)

Array in c++
Array in c++Array in c++
Array in c++
 
Sets in python
Sets in pythonSets in python
Sets in python
 
Binary Search - Design & Analysis of Algorithms
Binary Search - Design & Analysis of AlgorithmsBinary Search - Design & Analysis of Algorithms
Binary Search - Design & Analysis of Algorithms
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
 
SEARCHING AND SORTING ALGORITHMS
SEARCHING AND SORTING ALGORITHMSSEARCHING AND SORTING ALGORITHMS
SEARCHING AND SORTING ALGORITHMS
 
List in Python
List in PythonList in Python
List in Python
 
Queue in Data Structure
Queue in Data Structure Queue in Data Structure
Queue in Data Structure
 
Python – Object Oriented Programming
Python – Object Oriented Programming Python – Object Oriented Programming
Python – Object Oriented Programming
 
Python exception handling
Python   exception handlingPython   exception handling
Python exception handling
 
Deque and its applications
Deque and its applicationsDeque and its applications
Deque and its applications
 
Queue data structure
Queue data structureQueue data structure
Queue data structure
 
Doubly Linked List
Doubly Linked ListDoubly Linked List
Doubly Linked List
 
Python set
Python setPython set
Python set
 
Introduction to Recursion (Python)
Introduction to Recursion (Python)Introduction to Recursion (Python)
Introduction to Recursion (Python)
 
Java thread life cycle
Java thread life cycleJava thread life cycle
Java thread life cycle
 
Python Programming
Python Programming Python Programming
Python Programming
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
Binary Search Tree
Binary Search TreeBinary Search Tree
Binary Search Tree
 
Python programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphismPython programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphism
 
THREADED BINARY TREE AND BINARY SEARCH TREE
THREADED BINARY TREE AND BINARY SEARCH TREETHREADED BINARY TREE AND BINARY SEARCH TREE
THREADED BINARY TREE AND BINARY SEARCH TREE
 

En vedette

Object Oriented Programming with Real World Examples
Object Oriented Programming with Real World ExamplesObject Oriented Programming with Real World Examples
Object Oriented Programming with Real World ExamplesOXUS 20
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with pythonArslan Arshad
 
Decorators in Python
Decorators in PythonDecorators in Python
Decorators in PythonBen James
 
Python Programming - VI. Classes and Objects
Python Programming - VI. Classes and ObjectsPython Programming - VI. Classes and Objects
Python Programming - VI. Classes and ObjectsRanel Padon
 
Object oriented programming Fundamental Concepts
Object oriented programming Fundamental ConceptsObject oriented programming Fundamental Concepts
Object oriented programming Fundamental ConceptsBharat Kalia
 
Creating Objects in Python
Creating Objects in PythonCreating Objects in Python
Creating Objects in PythonDamian T. Gordon
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slotsmha4
 
Classes & object
Classes & objectClasses & object
Classes & objectDaman Toor
 
Metaclass Programming in Python
Metaclass Programming in PythonMetaclass Programming in Python
Metaclass Programming in PythonJuan-Manuel Gimeno
 
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...P3 InfoTech Solutions Pvt. Ltd.
 
Introduction To Programming with Python
Introduction To Programming with PythonIntroduction To Programming with Python
Introduction To Programming with PythonSushant Mane
 
Boost your django admin with Grappelli
Boost your django admin with GrappelliBoost your django admin with Grappelli
Boost your django admin with GrappelliAndy Dai
 
Visualizing Relationships between Python objects - EuroPython 2008
Visualizing Relationships between Python objects - EuroPython 2008Visualizing Relationships between Python objects - EuroPython 2008
Visualizing Relationships between Python objects - EuroPython 2008Dinu Gherman
 
HT16 - DA361A - OOP med Python
HT16 - DA361A - OOP med PythonHT16 - DA361A - OOP med Python
HT16 - DA361A - OOP med PythonAnton Tibblin
 
Data Structure: Algorithm and analysis
Data Structure: Algorithm and analysisData Structure: Algorithm and analysis
Data Structure: Algorithm and analysisDr. Rajdeep Chatterjee
 
CLTL python course: Object Oriented Programming (1/3)
CLTL python course: Object Oriented Programming (1/3)CLTL python course: Object Oriented Programming (1/3)
CLTL python course: Object Oriented Programming (1/3)Rubén Izquierdo Beviá
 

En vedette (20)

Python Objects
Python ObjectsPython Objects
Python Objects
 
Object Oriented Programming with Real World Examples
Object Oriented Programming with Real World ExamplesObject Oriented Programming with Real World Examples
Object Oriented Programming with Real World Examples
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with python
 
Decorators in Python
Decorators in PythonDecorators in Python
Decorators in Python
 
Python Programming - VI. Classes and Objects
Python Programming - VI. Classes and ObjectsPython Programming - VI. Classes and Objects
Python Programming - VI. Classes and Objects
 
Object oriented programming Fundamental Concepts
Object oriented programming Fundamental ConceptsObject oriented programming Fundamental Concepts
Object oriented programming Fundamental Concepts
 
Creating Objects in Python
Creating Objects in PythonCreating Objects in Python
Creating Objects in Python
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
Classes & object
Classes & objectClasses & object
Classes & object
 
PythonOOP
PythonOOPPythonOOP
PythonOOP
 
Metaclass Programming in Python
Metaclass Programming in PythonMetaclass Programming in Python
Metaclass Programming in Python
 
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
 
Introduction To Programming with Python
Introduction To Programming with PythonIntroduction To Programming with Python
Introduction To Programming with Python
 
Boost your django admin with Grappelli
Boost your django admin with GrappelliBoost your django admin with Grappelli
Boost your django admin with Grappelli
 
Visualizing Relationships between Python objects - EuroPython 2008
Visualizing Relationships between Python objects - EuroPython 2008Visualizing Relationships between Python objects - EuroPython 2008
Visualizing Relationships between Python objects - EuroPython 2008
 
HT16 - DA361A - OOP med Python
HT16 - DA361A - OOP med PythonHT16 - DA361A - OOP med Python
HT16 - DA361A - OOP med Python
 
Python avancé : Classe et objet
Python avancé : Classe et objetPython avancé : Classe et objet
Python avancé : Classe et objet
 
Data Structure: Algorithm and analysis
Data Structure: Algorithm and analysisData Structure: Algorithm and analysis
Data Structure: Algorithm and analysis
 
Python Programming Essentials - M8 - String Methods
Python Programming Essentials - M8 - String MethodsPython Programming Essentials - M8 - String Methods
Python Programming Essentials - M8 - String Methods
 
CLTL python course: Object Oriented Programming (1/3)
CLTL python course: Object Oriented Programming (1/3)CLTL python course: Object Oriented Programming (1/3)
CLTL python course: Object Oriented Programming (1/3)
 

Similaire à Python Programming Essentials - M20 - Classes and Objects

Python-oop
Python-oopPython-oop
Python-oopRTS Tech
 
Learning C++ - Class 4
Learning C++ - Class 4Learning C++ - Class 4
Learning C++ - Class 4Ali Aminian
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHPVibrant Technologies & Computers
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲Mohammad Reza Kamalifard
 
Advanced Python, Part 1
Advanced Python, Part 1Advanced Python, Part 1
Advanced Python, Part 1Zaar Hai
 
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.pdfSudhanshiBakre1
 
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.pdfSudhanshiBakre1
 
Intro to iOS Development • Made by Many
Intro to iOS Development • Made by ManyIntro to iOS Development • Made by Many
Intro to iOS Development • Made by Manykenatmxm
 
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.pptxsantoshkumar811204
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.pptDeepVala5
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Introduction to c_plus_plus
Introduction to c_plus_plusIntroduction to c_plus_plus
Introduction to c_plus_plusSayed Ahmed
 
Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)Sayed Ahmed
 
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.pptmuneshwarbisen1
 

Similaire à Python Programming Essentials - M20 - Classes and Objects (20)

C#2
C#2C#2
C#2
 
Inheritance.ppt
Inheritance.pptInheritance.ppt
Inheritance.ppt
 
Python-oop
Python-oopPython-oop
Python-oop
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
 
Learning C++ - Class 4
Learning C++ - Class 4Learning C++ - Class 4
Learning C++ - Class 4
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHP
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
 
Python advance
Python advancePython advance
Python advance
 
Advanced Python, Part 1
Advanced Python, Part 1Advanced Python, Part 1
Advanced Python, Part 1
 
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
 
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
 
Intro to iOS Development • Made by Many
Intro to iOS Development • Made by ManyIntro to iOS Development • Made by Many
Intro to iOS Development • Made by Many
 
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
 
Unit 1 Part - 3 constructor Overloading Static.ppt
Unit 1 Part - 3  constructor Overloading Static.pptUnit 1 Part - 3  constructor Overloading Static.ppt
Unit 1 Part - 3 constructor Overloading Static.ppt
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Introduction to c_plus_plus
Introduction to c_plus_plusIntroduction to c_plus_plus
Introduction to c_plus_plus
 
Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)
 
Java Reflection Concept and Working
Java Reflection Concept and WorkingJava Reflection Concept and Working
Java Reflection Concept and Working
 
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
 
.NET F# Class constructor
.NET F# Class constructor.NET F# Class constructor
.NET F# Class constructor
 

Plus de P3 InfoTech Solutions Pvt. Ltd.

Python Programming Essentials - M44 - Overview of Web Development
Python Programming Essentials - M44 - Overview of Web DevelopmentPython Programming Essentials - M44 - Overview of Web Development
Python Programming Essentials - M44 - Overview of Web DevelopmentP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M40 - Invoking External Programs
Python Programming Essentials - M40 - Invoking External ProgramsPython Programming Essentials - M40 - Invoking External Programs
Python Programming Essentials - M40 - Invoking External ProgramsP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M37 - Brief Overview of Misc Concepts
Python Programming Essentials - M37 - Brief Overview of Misc ConceptsPython Programming Essentials - M37 - Brief Overview of Misc Concepts
Python Programming Essentials - M37 - Brief Overview of Misc ConceptsP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M35 - Iterators & Generators
Python Programming Essentials - M35 - Iterators & GeneratorsPython Programming Essentials - M35 - Iterators & Generators
Python Programming Essentials - M35 - Iterators & GeneratorsP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M34 - List Comprehensions
Python Programming Essentials - M34 - List ComprehensionsPython Programming Essentials - M34 - List Comprehensions
Python Programming Essentials - M34 - List ComprehensionsP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M29 - Python Interpreter and Files
Python Programming Essentials - M29 - Python Interpreter and FilesPython Programming Essentials - M29 - Python Interpreter and Files
Python Programming Essentials - M29 - Python Interpreter and FilesP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M28 - Debugging with pdb
Python Programming Essentials - M28 - Debugging with pdbPython Programming Essentials - M28 - Debugging with pdb
Python Programming Essentials - M28 - Debugging with pdbP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modulesPython Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modulesP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception HandlingPython Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception HandlingP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M18 - Modules and Packages
Python Programming Essentials - M18 - Modules and PackagesPython Programming Essentials - M18 - Modules and Packages
Python Programming Essentials - M18 - Modules and PackagesP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and LoopsPython Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and LoopsP3 InfoTech Solutions Pvt. Ltd.
 

Plus de P3 InfoTech Solutions Pvt. Ltd. (20)

Python Programming Essentials - M44 - Overview of Web Development
Python Programming Essentials - M44 - Overview of Web DevelopmentPython Programming Essentials - M44 - Overview of Web Development
Python Programming Essentials - M44 - Overview of Web Development
 
Python Programming Essentials - M40 - Invoking External Programs
Python Programming Essentials - M40 - Invoking External ProgramsPython Programming Essentials - M40 - Invoking External Programs
Python Programming Essentials - M40 - Invoking External Programs
 
Python Programming Essentials - M39 - Unit Testing
Python Programming Essentials - M39 - Unit TestingPython Programming Essentials - M39 - Unit Testing
Python Programming Essentials - M39 - Unit Testing
 
Python Programming Essentials - M37 - Brief Overview of Misc Concepts
Python Programming Essentials - M37 - Brief Overview of Misc ConceptsPython Programming Essentials - M37 - Brief Overview of Misc Concepts
Python Programming Essentials - M37 - Brief Overview of Misc Concepts
 
Python Programming Essentials - M35 - Iterators & Generators
Python Programming Essentials - M35 - Iterators & GeneratorsPython Programming Essentials - M35 - Iterators & Generators
Python Programming Essentials - M35 - Iterators & Generators
 
Python Programming Essentials - M34 - List Comprehensions
Python Programming Essentials - M34 - List ComprehensionsPython Programming Essentials - M34 - List Comprehensions
Python Programming Essentials - M34 - List Comprehensions
 
Python Programming Essentials - M31 - PEP 8
Python Programming Essentials - M31 - PEP 8Python Programming Essentials - M31 - PEP 8
Python Programming Essentials - M31 - PEP 8
 
Python Programming Essentials - M29 - Python Interpreter and Files
Python Programming Essentials - M29 - Python Interpreter and FilesPython Programming Essentials - M29 - Python Interpreter and Files
Python Programming Essentials - M29 - Python Interpreter and Files
 
Python Programming Essentials - M28 - Debugging with pdb
Python Programming Essentials - M28 - Debugging with pdbPython Programming Essentials - M28 - Debugging with pdb
Python Programming Essentials - M28 - Debugging with pdb
 
Python Programming Essentials - M27 - Logging module
Python Programming Essentials - M27 - Logging modulePython Programming Essentials - M27 - Logging module
Python Programming Essentials - M27 - Logging module
 
Python Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modulesPython Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modules
 
Python Programming Essentials - M24 - math module
Python Programming Essentials - M24 - math modulePython Programming Essentials - M24 - math module
Python Programming Essentials - M24 - math module
 
Python Programming Essentials - M23 - datetime module
Python Programming Essentials - M23 - datetime modulePython Programming Essentials - M23 - datetime module
Python Programming Essentials - M23 - datetime module
 
Python Programming Essentials - M22 - File Operations
Python Programming Essentials - M22 - File OperationsPython Programming Essentials - M22 - File Operations
Python Programming Essentials - M22 - File Operations
 
Python Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception HandlingPython Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception Handling
 
Python Programming Essentials - M18 - Modules and Packages
Python Programming Essentials - M18 - Modules and PackagesPython Programming Essentials - M18 - Modules and Packages
Python Programming Essentials - M18 - Modules and Packages
 
Python Programming Essentials - M17 - Functions
Python Programming Essentials - M17 - FunctionsPython Programming Essentials - M17 - Functions
Python Programming Essentials - M17 - Functions
 
Python Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and LoopsPython Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and Loops
 
Python Programming Essentials - M15 - References
Python Programming Essentials - M15 - ReferencesPython Programming Essentials - M15 - References
Python Programming Essentials - M15 - References
 
Python Programming Essentials - M14 - Dictionaries
Python Programming Essentials - M14 - DictionariesPython Programming Essentials - M14 - Dictionaries
Python Programming Essentials - M14 - Dictionaries
 

Python Programming Essentials - M20 - Classes and Objects

  • 1. http://www.skillbrew.com /Skillbrew Talent brewed by the industry itself Classes and Objects Pavan Verma @YinYangPavan Founder, P3 InfoTech Solutions Pvt. Ltd. 1 Python Programming Essentials
  • 2. © SkillBrew http://skillbrew.com Contents  Defining a class  Class attributes  Class methods  Class instances  __init__ method  self keyword  Accessing attributes and methods  Deleting attributes  Types of attributes  Inheritance  Method overriding  Calling parent functions 2
  • 3. © SkillBrew http://skillbrew.com Defining a class A class is a special data type which defines how to build a certain kind of object class className(): # statements Use the class keyword to define a class 3
  • 4. © SkillBrew http://skillbrew.com Defining a class class Calculator(): counter = 0 def __init__(self): pass def add(self): pass class keyword to define a class A class definition creates a class object from which class instances may be created 4
  • 5. © SkillBrew http://skillbrew.com Class Attributes class Calculator(): counter = 0 def __init__(self): pass def add(self): pass class attributes are just like variables 5
  • 6. © SkillBrew http://skillbrew.com Class Methods class Calculator(): counter = 0 def __init__(self): pass def add(self): pass class methods are functions invoked on an instance of the class 6
  • 7. © SkillBrew http://skillbrew.com Class Instances calc = Calculator() • In order to you use it we create an instance of class • Instances are objects created that use the class definition Just call the class definition like a function to create a class instance 7
  • 8. © SkillBrew http://skillbrew.com __init__ method • __init__ method is like an initialization constructor • When a class defines an __init__ () method, class instantiation automatically invokes __init__() method for the newly created class instance 8
  • 9. © SkillBrew http://skillbrew.com __init__ method (2) class Calculator(): counter = 0 def __init__(self, x=0, y=0): self.x = x self.y = y def add(self): pass calc = Calculator(10, 20) print calc.x print calc.y Output: 10 20 9
  • 10. © SkillBrew http://skillbrew.com self keyword • 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 • In other class methods, it refers to the instance whose method was called • Similar to the keyword this in Java or C++ 10
  • 11. © SkillBrew http://skillbrew.com Accessing attributes and methods Use the dot operator to access class attributes and methods calc = Calculator(10, 20) print calc.x print calc.y print calc.counter Output: 10 20 0 11
  • 12. © SkillBrew http://skillbrew.com Accessing attributes and methods (2) class Calculator(): counter = 0 def __init__(self, x=0, y=0): self.x = x self.y = y def add(self): return self.x + self.y calc = Calculator(10, 20) print calc.add() • 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 12
  • 13. © SkillBrew http://skillbrew.com Deleting Instances • 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 references to a piece of memory have gone out of scope. Automatically frees the memory. • Garbage collection works well, hence fewer memory leaks • There’s also no “destructor” method for classes. 13
  • 15. © SkillBrew http://skillbrew.com Two kinds of Attributes 1. class attributes 2. data attributes 15
  • 16. © SkillBrew http://skillbrew.com Data attributes class Calculator(): counter = 0 def __init__(self, x=0, y=0): self.x = x self.y = y def add(self): return self.x + self.y calc = Calculator(10, 20) print calc.x # 10 print calc.y # 20 calc2 = Calculator(15, 35) print calc2.x # 15 print calc2.y # 35 • Data attributes are variables owned by a particular instance • Each instance has its own value for data attributes 16
  • 17. © SkillBrew http://skillbrew.com Data attributes (2) class Calculator(): counter = 0 def __init__(self, x=0, y=0): self.x = x self.y = y calc = Calculator(10, 20) calc.z = calc.x + calc.y print calc.z print calc.__dict__ Output: 30 {'y': 20, 'x': 10, 'z': 30} 17 • In Python classes you don’t have a restriction of declaring all data attributes before hand, you can create data attributes at runtime anywhere • calc.z is an attribute which is defined at runtime outside the class definition
  • 18. © SkillBrew http://skillbrew.com Class attributes class Calculator(): counter = 0 def __init__(self, x=0, y=0): self.x = x self.y = y def add(self): self.__class__.counter += 1 return self.x + self.y calc = Calculator(10, 20) print calc.add() print calc.counter # 1 calc2 = Calculator(30, 40) print calc2.add() print calc2.counter # 2 • Access the class attribute using self.__class__.count er • Class attributes are shared among all instances 18
  • 19. © SkillBrew http://skillbrew.com Class attributes (2)  Class attributes are defined within a class definition and outside of any method  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 self.__class__.attribute_name 19
  • 20. © SkillBrew http://skillbrew.com Data attributes  Variable owned by a particular instance  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  Good for • Class-wide constants • Building counter of how many instances of the class have been made Data attributes vs Class attributes 20
  • 22. © SkillBrew http://skillbrew.com Inheritance class Shape(object): def name(self, shape): print "Shape: %s" % shape class Square(Shape): def area(self, side): return side**2 Shape is the parent class Square is the child class inherits Shape class Parent(object): pass class Child(Parent): pass 22
  • 23. © SkillBrew http://skillbrew.com Inheritance (2) class Shape(object): def name(self, shape): print "Shape: %s" % shape class Square(Shape): def area(self, side): return side**2 s = Square() s.name("square") print s.area(2) Output: Shape: square 4 Child class Square has access to Parent classes methods and attributes 23
  • 24. © SkillBrew http://skillbrew.com Method overriding class Shape(object): def name(self, shape): print "Shape: %s" % shape class Square(Shape): def name(self, shape): print "Child class Shape %s" % shape def area(self, side): return side**2 s = Square() s.name("square") print s.area(2) Output: Child class Shape square 4 24
  • 25. © SkillBrew http://skillbrew.com Calling the parent method class Shape(object): def name(self, shape): print "Shape: %s" % shape class Square(Shape): def name(self, shape): super(Square, self).name(shape) print "Child class Shape %s" % shape def area(self, side): return side**2 s = Square() s.name("square") Use super keyword to call parent class method super(ChildClass, self).method(args) 25
  • 26. © SkillBrew http://skillbrew.com Class & Static Methods class Calculator(object): counter = 0 def __init__(self, x=0, y=0): ... def add(self): ... @classmethod def update_counter(cls): cls.counter += 1 @staticmethod def show_help(): print 'This calculator can add' 26
  • 27. © SkillBrew http://skillbrew.com Resources  http://www.diveintopython.net/object_o riented_framework/defining_classes.html  http://docs.python.org/2/tutorial/classes .html  http://docs.python.org/2/library/function s.html#super 27