Python Crash Course Classes 3 rd year Bachelors V1.0 dd 03-09-2013 Hour 7.

Slides:



Advertisements
Similar presentations
Python Objects and Classes
Advertisements

Object-Oriented Programming
Object-Oriented Programming Python. OO Paradigm - Review Three Characteristics of OO Languages –Inheritance It isn’t necessary to build every class from.
Python Mini-Course University of Oklahoma Department of Psychology Lesson 28 Classes and Methods 6/17/09 Python Mini-Course: Lesson 28 1.
Python Mini-Course University of Oklahoma Department of Psychology Lesson 26 Classes and Objects 6/16/09 Python Mini-Course: Lesson 26 1.
OBJECT ORIENTED PROGRAMMING (OOP) IN PYTHON David Moodie.
1 Programming for Engineers in Python Autumn Lecture 5: Object Oriented Programming.
INFO 206 Lab Exercise 1 Introduction to Classes and Objects 1/18/2012i206 Lab 1 - Exercise1.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Python 3 Some material adapted from Upenn cis391 slides and other sources.
Computer Science 111 Fundamentals of Programming I Introduction to Programmer-Defined Classes.
Inheritance #1 First questions Similar to Python? What about visibility and encapsulation? – can an object of the child class access private members.
Guide to Programming with Python
Python 3 Some material adapted from Upenn cis391 slides and other sources.
I210 review (for final exam) Fall 2011, IUB. What’s in the Final Exam Multiple Choice (5) Short Answer (5) Program Completion (3) Note: A single-sided.
1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.
Centre for Computer Technology ICT115 Object Oriented Design and Programming Week 2 Intro to Classes Richard Salomon and Umesh Patel Centre for Information.
Inheritance. Inhertance Inheritance is used to indicate that one class will get most or all of its features from a parent class. class Dog(Pet): Make.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Chapter 11 Introduction to Classes Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
CSC1018F: Object Orientation, Exceptions and File Handling Diving into Python Ch. 5&6 Think Like a Comp. Scientist Ch
 Computer Science 1MD3 Introduction to Programming Michael Liut Ming Quan Fu Brandon.
Python: Classes By Matt Wufsus. Scopes and Namespaces A namespace is a mapping from names to objects. ◦Examples: the set of built-in names, such as the.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Introduction to Python III CSE-391: Artificial Intelligence University of Pennsylvania Matt Huenerfauth January 2005.
By: Chris Harvey Python Classes. Namespaces A mapping from names to objects Different namespaces have different mappings Namespaces have varying lifetimes.
Chapter 11 Introduction to Classes. "The Practice of Computing Using Python", Punch & Enbody, Copyright © 2013 Pearson Education, Inc. Code Listing 11.1.
OOP IN PHP `Object Oriented Programming in any language is the use of objects to represent functional parts of an application and real life entities. For.
An Introduction to Python Blake Brogdon. What is Python?  Python is an interpreted, interactive, object-oriented programming language. (from python.org)
 Computer Science 1MD3 Introduction to Programming Michael Liut Ming Quan Fu Brandon.
Introduction to OOP OOP = Object-Oriented Programming OOP is very simple in python but also powerful What is an object? data structure, and functions (methods)
CLASSES Python Workshop. Introduction  Compared with other programming languages, Python’s class mechanism adds classes with a minimum of new syntax.
P YTHON ’ S C LASSES Ian Wynyard. I NTRODUCTION TO C LASSES A class is the scope in which code is executed A class contains objects and functions that.
Overview The Basics – Python classes and objects Procedural vs OO Programming Entity modelling Operations / methods Program flow OOP Concepts and user-defined.
Introduction to Python III CIS 391: Artificial Intelligence Fall, 2008.
Chapter Object Oriented Programming (OOP) CSC1310 Fall 2009.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
 Computer Science 1MD3 Introduction to Programming Michael Liut Ming Quan Fu Brandon.
Object-Oriented Programming. Objectives Distinguish between object-oriented and procedure-oriented design. Define the terms class and object. Distinguish.
2 Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Guide to Programming with Python Chapter Eight (Part I) Object Oriented Programming; Classes, constructors, attributes, and methods.
Python – May 19 Review –What is the difference between: list, tuple, set, dictionary? –When is it appropriate to use each? Creating our own data types:
Basic Concepts of OOP.  Object-Oriented Programming (OOP) is a type of programming added to php5 that makes building complex, modular and reusable web.
Introduction to Classes Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
OOP Basics Classes & Methods (c) IDMS/SQL News
CSCI/CMPE 4341 Topic: Programming in Python Chapter 7: Introduction to Object- Oriented Programming in Python – Exercises Xiang Lian The University of.
CSC 231: Introduction to Data Structures Python and Objects – Day 3 Dr. Curry Guinn.
CMSC201 Computer Science I for Majors Lecture 25 – Classes
Introduction to Object-oriented Programming
Python 3 Some material adapted from Upenn cis391 slides and other sources.
Object Oriented Programming in Python: Defining Classes
COMPSCI 107 Computer Science Fundamentals
CSSE 120—Rose Hulman Institute of Technology
Software Development Java Classes and Methods
Copyright (c) 2017 by Dr. E. Horvath
Computer Science 111 Fundamentals of Programming I
Lecture VI Objects The OOP Concept Defining Classes Methods
Creating and Deleting Instances Access to Attributes and Methods
CHAPTER FIVE Classes.
Teach A-Level Computer Science: Object-Oriented Programming in Python
Overview of OOP Terminology
Computer Science 111 Fundamentals of Programming I
Python 3 Some material adapted from Upenn cis391 slides and other sources.
C++ Programming ㅎㅎ String OOP Class Constructor & Destructor.
G. Pullaiah College of Engineering and Technology
Object-Oriented Programming
CSE 231 Lab 11.
Lecture 18 Python OOP.
Presentation transcript:

Python Crash Course Classes 3 rd year Bachelors V1.0 dd Hour 7

Introduction to language - methods >>> a = [2, 5, 3, 6, 5] >>> a.sort() >>> print(a) [2, 3, 5, 5, 6] >>> a.count(3) 1 >>> a.count(5) 2 >>> a.reverse() >>> print(a) [6, 5, 5, 3, 2] >>> d = {‘black’: 100, ‘grey’: 50, ‘white’: 0} >>> d.values() [0, 50, 100] >>> s = ‘-‘.join((‘2009’, ‘07’, ‘07’)) >>> print(s)

Introduction to language - classes >>> class MyClass(object):... def __init__(self, x, y=1.0)... self.my_x = x... self.my_y = y def product():... return x*y... >>> m = MyClass(2, 4) >>> m.product() 8 >>> p = MyClass(5) >>> p.product() 5 >>> m.product() 8

Classes OOP terminology Class: A user-defined prototype for an object that defines a set of attributes that characterize any object of the class. The attributes are data members (class variables and instance variables) and methods, accessed via dot notation. Class variable: A variable that is shared by all instances of a class. Class variables are defined within a class but outside any of the class's methods. Class variables aren't used as frequently as instance variables are. Data member: A class variable or instance variable that holds data associated with a class and its objects. Function overloading: The assignment of more than one behavior to a particular function. The operation performed varies by the types of objects (arguments) involved. Instance variable: A variable that is defined inside a method and belongs only to the current instance of a class. Inheritance : The transfer of the characteristics of a class to other classes that are derived from it. Instance: An individual object of a certain class. An object obj that belongs to a class Circle, for example, is an instance of the class Circle. Instantiation : The creation of an instance of a class. Method : A special kind of function that is defined in a class definition. Object : A unique instance of a data structure that's defined by its class. An object comprises both data members (class variables and instance variables) and methods. Operator overloading: The assignment of more than one function to a particular operator.

Classes class Planet(object): 'Common base class for all planets' PlanetCount = 0 def __init__(self, name, mass): self.mass = mass self.name= name Planet.PlanetCount += 1 def displayCount(self): print "Total Planets %d" % Planet.PlanetCount def displayPlanet(self): print "Name : ", self.name, ", Mass: ", self.mass "This would create first object of Planet class" planet1 = Planet(“Earth", 5.972E24) "This would create second object of Planet class" planet2 = Planet(“Venus", 4.867E24)

Classes planet1.displayPlanet() Name: Earth, Mass: 5.972e+24 planet2.displayPlanet() Name: Venus, Mass: 4.867e+24 planet2.displayCount() Total Planets 2 planet1.satellites = 1 planet2.satellites = 0 del planet2.satellites hasattr(planet1, ‘satellites') # Returns true if 'satellites' attribute exists getattr(planet1, ‘satellites') # Returns value of 'satellites' attribute setattr(planet1, ‘satellites', 8) # Set attribute 'satellites' at 8 delattr(planetl, ‘satellites') # Delete attribute 'satellites'

Classes Built-in attributes Every Python class keeps following built-in attributes and they can be accessed using dot operator like any other attribute: __dict__ : Dictionary containing the class's namespace. __doc__ : Class documentation string, or None if undefined. __name__: Class name. __module__: Module name in which the class is defined. This attribute is "__main__" in interactive mode. __bases__ : A possibly empty tuple containing the base classes, in the order of their occurrence in the base class list. Planet.__doc__: Common base class for all Planets Planet.__name__: Planet Planet.__module__: __main__ Planet.__bases__: () Planet.__dict__: {'__module__': '__main__', 'displayCount':, 'PlanetCount': 2, 'displayPlanet':, '__doc__': 'Common base class for all Planets', '__init__': }

Classes Inheritance #!/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 Calling child constructor Calling child method Calling parent method Parent attribute : 200

Classes Overriding methods #!/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‘ Parent.myMethod(self) c = Child() # instance of child c.myMethod() # child calls overridden method Calling child method Calling parent method You can always override your parent class methods. One reason for overriding parent's methods is because you may want special or different functionality in your subclass.

Classes Overloading Methods SNMethod, Description & Sample Call 1 __init__ ( self [,args...] ) Constructor (with any optional arguments) Sample Call : obj = className(args) 2 __del__( self ) Destructor, deletes an object 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) #!/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 Vector(7,8)

Classes Data hiding #!/usr/bin/python class JustCounter: __secretCount = 0 def count(self): self.__secretCount += 1 print self.__secretCount counter = JustCounter() counter.count() print counter.__secretCount 1 2 Traceback (most recent call last): File "test.py", line 12, in print counter.__secretCount AttributeError: JustCounter instance has no attribute '__secretCount' An object's attributes may or may not be visible outside the class definition. For these cases, you can name attributes with a double underscore prefix, and those attributes will not be directly visible to outsiders:

Introduction to language End