Movatterモバイル変換


[0]ホーム

URL:


2,370 views

Python Programming Essentials - M20 - Classes and Objects

This document discusses classes and objects in Python. It defines a Calculator class and demonstrates how to create class attributes, methods, and instances. It explains the __init__ method, self keyword, and how to access attributes and methods. It also covers data attributes versus class attributes, inheritance, method overriding, and calling parent methods. The document provides examples to illustrate these object-oriented programming concepts in Python.

Embed presentation

http://www.skillbrew.com/SkillbrewTalent brewed by theindustry itselfClasses and ObjectsPavan Verma@YinYangPavanFounder, P3 InfoTech Solutions Pvt. Ltd.1Python Programming Essentials
© SkillBrew http://skillbrew.comContents 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 functions2
© SkillBrew http://skillbrew.comDefining a classA class is a special data type which defines howto build a certain kind of objectclass className():# statementsUse the class keyword to define a class3
© SkillBrew http://skillbrew.comDefining a classclass Calculator():counter = 0def __init__(self):passdef add(self):passclass keyword todefine a classA class definition creates a class object from whichclass instances may be created4
© SkillBrew http://skillbrew.comClass Attributesclass Calculator():counter = 0def __init__(self):passdef add(self):passclass attributes arejust like variables5
© SkillBrew http://skillbrew.comClass Methodsclass Calculator():counter = 0def __init__(self):passdef add(self):passclass methods arefunctions invoked on aninstance of the class6
© SkillBrew http://skillbrew.comClass Instancescalc = Calculator()• In order to you use it we create an instance ofclass• Instances are objects created that use the classdefinitionJust call the class definition like a function to createa class instance7
© SkillBrew http://skillbrew.com__init__ method• __init__ method is like an initializationconstructor• When a class defines an __init__ ()method, class instantiation automatically invokes__init__() method for the newly createdclass instance8
© SkillBrew http://skillbrew.com__init__ method (2)class Calculator():counter = 0def __init__(self, x=0, y=0):self.x = xself.y = ydef add(self):passcalc = Calculator(10, 20)print calc.xprint calc.yOutput:10209
© SkillBrew http://skillbrew.comself keyword• The first argument of every method is a referenceto the current instance of the class• By convention, we name this argument self• In __init__, self refers to the object currentlybeing created• In other class methods, it refers to the instancewhose method was called• Similar to the keyword this in Java or C++10
© SkillBrew http://skillbrew.comAccessing attributes and methodsUse the dot operator to access class attributes andmethodscalc = Calculator(10, 20)print calc.xprint calc.yprint calc.counterOutput:1020011
© SkillBrew http://skillbrew.comAccessing attributes and methods (2)class Calculator():counter = 0def __init__(self, x=0, y=0):self.x = xself.y = ydef add(self):return self.x + self.ycalc = Calculator(10, 20)print calc.add()• Although you must specify selfexplicitly when defining themethod, you don’t include itwhen calling the method• Python passes it for youautomatically12
© SkillBrew http://skillbrew.comDeleting Instances• When you are done with an object , you don’t haveto delete or free it explicitly• Python has automatic garbage collection• Python will automatically detect when all referencesto a piece of memory have gone out of scope.Automatically frees the memory.• Garbage collection works well, hence fewer memoryleaks• There’s also no “destructor” method for classes.13
© SkillBrew http://skillbrew.comAttributes14
© SkillBrew http://skillbrew.comTwo kinds of Attributes1. class attributes2. data attributes15
© SkillBrew http://skillbrew.comData attributesclass Calculator():counter = 0def __init__(self, x=0, y=0):self.x = xself.y = ydef add(self):return self.x + self.ycalc = Calculator(10, 20)print calc.x # 10print calc.y # 20calc2 = Calculator(15, 35)print calc2.x # 15print calc2.y # 35• Data attributes arevariables owned by aparticular instance• Each instance has its ownvalue for data attributes16
© SkillBrew http://skillbrew.comData attributes (2)class Calculator():counter = 0def __init__(self, x=0, y=0):self.x = xself.y = ycalc = Calculator(10, 20)calc.z = calc.x + calc.yprint calc.zprint calc.__dict__Output:30{'y': 20, 'x': 10, 'z': 30}17• In Python classes you don’thave a restriction ofdeclaring all dataattributes before hand,you can create dataattributes at runtimeanywhere• calc.z is an attributewhich is defined atruntime outside the classdefinition
© SkillBrew http://skillbrew.comClass attributesclass Calculator():counter = 0def __init__(self, x=0, y=0):self.x = xself.y = ydef add(self):self.__class__.counter += 1return self.x + self.ycalc = Calculator(10, 20)print calc.add()print calc.counter # 1calc2 = Calculator(30, 40)print calc2.add()print calc2.counter # 2• Access the classattribute usingself.__class__.counter• Class attributes areshared among allinstances18
© SkillBrew http://skillbrew.comClass attributes (2) Class attributes are defined within a class definitionand outside of any method Because all instances of a class share one copy of aclass attribute, when any instance changes it, thevalue is changed for all instancesself.__class__.attribute_name19
© SkillBrew http://skillbrew.comData attributes Variable owned by aparticular instance Each instance has its ownvalue for it These are the mostcommon kind of attributeClass attributes Owned by the class as awhole All class instances share thesame value for it Good for• Class-wide constants• Building counter of howmany instances of theclass have been madeData attributes vs Class attributes20
© SkillBrew http://skillbrew.comInheritance21
© SkillBrew http://skillbrew.comInheritanceclass Shape(object):def name(self, shape):print "Shape: %s" % shapeclass Square(Shape):def area(self, side):return side**2Shape is theparent classSquare is thechild class inheritsShapeclass Parent(object):passclass Child(Parent):pass22
© SkillBrew http://skillbrew.comInheritance (2)class Shape(object):def name(self, shape):print "Shape: %s" % shapeclass Square(Shape):def area(self, side):return side**2s = Square()s.name("square")print s.area(2)Output:Shape: square4Child class Square has access toParent classes methods andattributes23
© SkillBrew http://skillbrew.comMethod overridingclass Shape(object):def name(self, shape):print "Shape: %s" % shapeclass Square(Shape):def name(self, shape):print "Child class Shape %s" % shapedef area(self, side):return side**2s = Square()s.name("square")print s.area(2)Output:Child class Shape square424
© SkillBrew http://skillbrew.comCalling the parent methodclass Shape(object):def name(self, shape):print "Shape: %s" % shapeclass Square(Shape):def name(self, shape):super(Square, self).name(shape)print "Child class Shape %s" % shapedef area(self, side):return side**2s = Square()s.name("square")Use super keyword to call parent class methodsuper(ChildClass, self).method(args)25
© SkillBrew http://skillbrew.comClass & Static Methodsclass Calculator(object):counter = 0def __init__(self, x=0, y=0):...def add(self):...@classmethoddef update_counter(cls):cls.counter += 1@staticmethoddef show_help():print 'This calculator canadd'26
© SkillBrew http://skillbrew.comResources http://www.diveintopython.net/object_oriented_framework/defining_classes.html http://docs.python.org/2/tutorial/classes.html http://docs.python.org/2/library/functions.html#super27

Recommended

PPTX
Threaded Binary Tree.pptx
PPTX
Tree in data structure
PPTX
Data Structures (CS8391)
PPTX
Topological Sorting
PPT
Binary Search Tree and AVL
PPTX
Binomial heap presentation
PPTX
Introduction to numpy Session 1
PPT
Regular Languages
PDF
Trees, Binary Search Tree, AVL Tree in Data Structures
PPT
Queue AS an ADT (Abstract Data Type)
PPTX
Depth first traversal(data structure algorithms)
PPT
Trees
PPTX
Binary Heap Tree, Data Structure
PPTX
Project on stack Data structure
PPTX
Types of grammer - TOC
PPT
Graphs bfs dfs
PDF
Longest common subsequence
PPTX
Queue Implementation Using Array & Linked List
 
PDF
Abstract Data Types
PDF
Double ended queue
PDF
Mask-RCNN for Instance Segmentation
PPTX
Stack and Queue
PPT
Max flow min cut
PDF
9 python data structure-2
PPTX
Red black trees
PPTX
Binary Search Tree
PDF
Fibonacci Heap
PPT
Python Objects
PDF
Object Oriented Programming with Real World Examples

More Related Content

PPTX
Threaded Binary Tree.pptx
PPTX
Tree in data structure
PPTX
Data Structures (CS8391)
PPTX
Topological Sorting
PPT
Binary Search Tree and AVL
PPTX
Binomial heap presentation
PPTX
Introduction to numpy Session 1
Threaded Binary Tree.pptx
Tree in data structure
Data Structures (CS8391)
Topological Sorting
Binary Search Tree and AVL
Binomial heap presentation
Introduction to numpy Session 1

What's hot

PPT
Regular Languages
PDF
Trees, Binary Search Tree, AVL Tree in Data Structures
PPT
Queue AS an ADT (Abstract Data Type)
PPTX
Depth first traversal(data structure algorithms)
PPT
Trees
PPTX
Binary Heap Tree, Data Structure
PPTX
Project on stack Data structure
PPTX
Types of grammer - TOC
PPT
Graphs bfs dfs
PDF
Longest common subsequence
PPTX
Queue Implementation Using Array & Linked List
 
PDF
Abstract Data Types
PDF
Double ended queue
PDF
Mask-RCNN for Instance Segmentation
PPTX
Stack and Queue
PPT
Max flow min cut
PDF
9 python data structure-2
PPTX
Red black trees
PPTX
Binary Search Tree
PDF
Fibonacci Heap
Regular Languages
Trees, Binary Search Tree, AVL Tree in Data Structures
Queue AS an ADT (Abstract Data Type)
Depth first traversal(data structure algorithms)
Trees
Binary Heap Tree, Data Structure
Project on stack Data structure
Types of grammer - TOC
Graphs bfs dfs
Longest common subsequence
Queue Implementation Using Array & Linked List
 
Abstract Data Types
Double ended queue
Mask-RCNN for Instance Segmentation
Stack and Queue
Max flow min cut
9 python data structure-2
Red black trees
Binary Search Tree
Fibonacci Heap

Viewers also liked

PPT
Python Objects
PDF
Object Oriented Programming with Real World Examples
PPTX
Object oriented programming with python
ODP
Decorators in Python
PDF
Python Programming - VI. Classes and Objects
PPTX
Object oriented programming Fundamental Concepts
PPTX
Creating Objects in Python
PPTX
03 object-classes-pbl-4-slots
 
PPTX
Classes & object
PDF
PythonOOP
PDF
Metaclass Programming in Python
PPTX
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
PDF
Introduction To Programming with Python
PDF
Boost your django admin with Grappelli
PDF
Visualizing Relationships between Python objects - EuroPython 2008
PDF
HT16 - DA361A - OOP med Python
PDF
Python avancé : Classe et objet
PDF
Data Structure: Algorithm and analysis
PPTX
Python Programming Essentials - M8 - String Methods
PDF
CLTL python course: Object Oriented Programming (1/3)
Python Objects
Object Oriented Programming with Real World Examples
Object oriented programming with python
Decorators in Python
Python Programming - VI. Classes and Objects
Object oriented programming Fundamental Concepts
Creating Objects in Python
03 object-classes-pbl-4-slots
 
Classes & object
PythonOOP
Metaclass Programming in Python
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
Introduction To Programming with Python
Boost your django admin with Grappelli
Visualizing Relationships between Python objects - EuroPython 2008
HT16 - DA361A - OOP med Python
Python avancé : Classe et objet
Data Structure: Algorithm and analysis
Python Programming Essentials - M8 - String Methods
CLTL python course: Object Oriented Programming (1/3)

Similar to Python Programming Essentials - M20 - Classes and Objects

PDF
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
PDF
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
PPTX
Object Oriented Programming.pptx
PPTX
Module-5-Classes and Objects for Python Programming.pptx
PPT
Introduction to Python - Part Three
PPT
Lecture topic - Python class lecture.ppt
PPT
Lecture on Python class -lecture123456.ppt
PPT
python3.ppt for taking presentation to your peers
PPTX
OOPS-PYTHON.pptx OOPS IN PYTHON APPLIED PROGRAMMING
PPTX
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
PPT
Python3
PPT
Chap 3 Python Object Oriented Programming - Copy.ppt
PDF
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PPTX
مقدمة بايثون .pptx
PPTX
VTU Python Module 5 , Class and Objects and Debugging
PPTX
Basic_concepts_of_OOPS_in_Python.pptx
PPTX
classes and objects of python object oriented
PPTX
Python advance
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
Object Oriented Programming.pptx
Module-5-Classes and Objects for Python Programming.pptx
Introduction to Python - Part Three
Lecture topic - Python class lecture.ppt
Lecture on Python class -lecture123456.ppt
python3.ppt for taking presentation to your peers
OOPS-PYTHON.pptx OOPS IN PYTHON APPLIED PROGRAMMING
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
Python3
Chap 3 Python Object Oriented Programming - Copy.ppt
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
مقدمة بايثون .pptx
VTU Python Module 5 , Class and Objects and Debugging
Basic_concepts_of_OOPS_in_Python.pptx
classes and objects of python object oriented
Python advance

More from P3 InfoTech Solutions Pvt. Ltd.

PPTX
Python Programming Essentials - M44 - Overview of Web Development
PPTX
Python Programming Essentials - M40 - Invoking External Programs
PPTX
Python Programming Essentials - M39 - Unit Testing
PPTX
Python Programming Essentials - M37 - Brief Overview of Misc Concepts
PPTX
Python Programming Essentials - M35 - Iterators & Generators
PPTX
Python Programming Essentials - M34 - List Comprehensions
PPTX
Python Programming Essentials - M31 - PEP 8
PPTX
Python Programming Essentials - M29 - Python Interpreter and Files
PPTX
Python Programming Essentials - M28 - Debugging with pdb
PPTX
Python Programming Essentials - M27 - Logging module
PPTX
Python Programming Essentials - M25 - os and sys modules
PPTX
Python Programming Essentials - M24 - math module
PPTX
Python Programming Essentials - M23 - datetime module
PPTX
Python Programming Essentials - M22 - File Operations
PPTX
Python Programming Essentials - M21 - Exception Handling
PPTX
Python Programming Essentials - M18 - Modules and Packages
PPTX
Python Programming Essentials - M17 - Functions
PPTX
Python Programming Essentials - M16 - Control Flow Statements and Loops
PPTX
Python Programming Essentials - M15 - References
PPTX
Python Programming Essentials - M14 - Dictionaries
Python Programming Essentials - M44 - Overview of Web Development
Python Programming Essentials - M40 - Invoking External Programs
Python Programming Essentials - M39 - Unit Testing
Python Programming Essentials - M37 - Brief Overview of Misc Concepts
Python Programming Essentials - M35 - Iterators & Generators
Python Programming Essentials - M34 - List Comprehensions
Python Programming Essentials - M31 - PEP 8
Python Programming Essentials - M29 - Python Interpreter and Files
Python Programming Essentials - M28 - Debugging with pdb
Python Programming Essentials - M27 - Logging module
Python Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M24 - math module
Python Programming Essentials - M23 - datetime module
Python Programming Essentials - M22 - File Operations
Python Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M18 - Modules and Packages
Python Programming Essentials - M17 - Functions
Python Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M15 - References
Python Programming Essentials - M14 - Dictionaries

Python Programming Essentials - M20 - Classes and Objects

  • 1.
    http://www.skillbrew.com/SkillbrewTalent brewed bytheindustry itselfClasses and ObjectsPavan Verma@YinYangPavanFounder, P3 InfoTech Solutions Pvt. Ltd.1Python Programming Essentials
  • 2.
    © SkillBrew http://skillbrew.comContents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 functions2
  • 3.
    © SkillBrew http://skillbrew.comDefininga classA class is a special data type which defines howto build a certain kind of objectclass className():# statementsUse the class keyword to define a class3
  • 4.
    © SkillBrew http://skillbrew.comDefininga classclass Calculator():counter = 0def __init__(self):passdef add(self):passclass keyword todefine a classA class definition creates a class object from whichclass instances may be created4
  • 5.
    © SkillBrew http://skillbrew.comClassAttributesclass Calculator():counter = 0def __init__(self):passdef add(self):passclass attributes arejust like variables5
  • 6.
    © SkillBrew http://skillbrew.comClassMethodsclass Calculator():counter = 0def __init__(self):passdef add(self):passclass methods arefunctions invoked on aninstance of the class6
  • 7.
    © SkillBrew http://skillbrew.comClassInstancescalc = Calculator()• In order to you use it we create an instance ofclass• Instances are objects created that use the classdefinitionJust call the class definition like a function to createa class instance7
  • 8.
    © SkillBrew http://skillbrew.com__init__method• __init__ method is like an initializationconstructor• When a class defines an __init__ ()method, class instantiation automatically invokes__init__() method for the newly createdclass instance8
  • 9.
    © SkillBrew http://skillbrew.com__init__method (2)class Calculator():counter = 0def __init__(self, x=0, y=0):self.x = xself.y = ydef add(self):passcalc = Calculator(10, 20)print calc.xprint calc.yOutput:10209
  • 10.
    © SkillBrew http://skillbrew.comselfkeyword• The first argument of every method is a referenceto the current instance of the class• By convention, we name this argument self• In __init__, self refers to the object currentlybeing created• In other class methods, it refers to the instancewhose method was called• Similar to the keyword this in Java or C++10
  • 11.
    © SkillBrew http://skillbrew.comAccessingattributes and methodsUse the dot operator to access class attributes andmethodscalc = Calculator(10, 20)print calc.xprint calc.yprint calc.counterOutput:1020011
  • 12.
    © SkillBrew http://skillbrew.comAccessingattributes and methods (2)class Calculator():counter = 0def __init__(self, x=0, y=0):self.x = xself.y = ydef add(self):return self.x + self.ycalc = Calculator(10, 20)print calc.add()• Although you must specify selfexplicitly when defining themethod, you don’t include itwhen calling the method• Python passes it for youautomatically12
  • 13.
    © SkillBrew http://skillbrew.comDeletingInstances• When you are done with an object , you don’t haveto delete or free it explicitly• Python has automatic garbage collection• Python will automatically detect when all referencesto a piece of memory have gone out of scope.Automatically frees the memory.• Garbage collection works well, hence fewer memoryleaks• There’s also no “destructor” method for classes.13
  • 14.
  • 15.
    © SkillBrew http://skillbrew.comTwokinds of Attributes1. class attributes2. data attributes15
  • 16.
    © SkillBrew http://skillbrew.comDataattributesclass Calculator():counter = 0def __init__(self, x=0, y=0):self.x = xself.y = ydef add(self):return self.x + self.ycalc = Calculator(10, 20)print calc.x # 10print calc.y # 20calc2 = Calculator(15, 35)print calc2.x # 15print calc2.y # 35• Data attributes arevariables owned by aparticular instance• Each instance has its ownvalue for data attributes16
  • 17.
    © SkillBrew http://skillbrew.comDataattributes (2)class Calculator():counter = 0def __init__(self, x=0, y=0):self.x = xself.y = ycalc = Calculator(10, 20)calc.z = calc.x + calc.yprint calc.zprint calc.__dict__Output:30{'y': 20, 'x': 10, 'z': 30}17• In Python classes you don’thave a restriction ofdeclaring all dataattributes before hand,you can create dataattributes at runtimeanywhere• calc.z is an attributewhich is defined atruntime outside the classdefinition
  • 18.
    © SkillBrew http://skillbrew.comClassattributesclass Calculator():counter = 0def __init__(self, x=0, y=0):self.x = xself.y = ydef add(self):self.__class__.counter += 1return self.x + self.ycalc = Calculator(10, 20)print calc.add()print calc.counter # 1calc2 = Calculator(30, 40)print calc2.add()print calc2.counter # 2• Access the classattribute usingself.__class__.counter• Class attributes areshared among allinstances18
  • 19.
    © SkillBrew http://skillbrew.comClassattributes (2) Class attributes are defined within a class definitionand outside of any method Because all instances of a class share one copy of aclass attribute, when any instance changes it, thevalue is changed for all instancesself.__class__.attribute_name19
  • 20.
    © SkillBrew http://skillbrew.comDataattributes Variable owned by aparticular instance Each instance has its ownvalue for it These are the mostcommon kind of attributeClass attributes Owned by the class as awhole All class instances share thesame value for it Good for• Class-wide constants• Building counter of howmany instances of theclass have been madeData attributes vs Class attributes20
  • 21.
  • 22.
    © SkillBrew http://skillbrew.comInheritanceclassShape(object):def name(self, shape):print "Shape: %s" % shapeclass Square(Shape):def area(self, side):return side**2Shape is theparent classSquare is thechild class inheritsShapeclass Parent(object):passclass Child(Parent):pass22
  • 23.
    © SkillBrew http://skillbrew.comInheritance(2)class Shape(object):def name(self, shape):print "Shape: %s" % shapeclass Square(Shape):def area(self, side):return side**2s = Square()s.name("square")print s.area(2)Output:Shape: square4Child class Square has access toParent classes methods andattributes23
  • 24.
    © SkillBrew http://skillbrew.comMethodoverridingclass Shape(object):def name(self, shape):print "Shape: %s" % shapeclass Square(Shape):def name(self, shape):print "Child class Shape %s" % shapedef area(self, side):return side**2s = Square()s.name("square")print s.area(2)Output:Child class Shape square424
  • 25.
    © SkillBrew http://skillbrew.comCallingthe parent methodclass Shape(object):def name(self, shape):print "Shape: %s" % shapeclass Square(Shape):def name(self, shape):super(Square, self).name(shape)print "Child class Shape %s" % shapedef area(self, side):return side**2s = Square()s.name("square")Use super keyword to call parent class methodsuper(ChildClass, self).method(args)25
  • 26.
    © SkillBrew http://skillbrew.comClass& Static Methodsclass Calculator(object):counter = 0def __init__(self, x=0, y=0):...def add(self):...@classmethoddef update_counter(cls):cls.counter += 1@staticmethoddef show_help():print 'This calculator canadd'26
  • 27.
    © SkillBrew http://skillbrew.comResourceshttp://www.diveintopython.net/object_oriented_framework/defining_classes.html http://docs.python.org/2/tutorial/classes.html http://docs.python.org/2/library/functions.html#super27

[8]ページ先頭

©2009-2025 Movatter.jp