Python programming - Defining Classes

Slides:



Advertisements
Similar presentations
Classes and Objects. What is Design? The parts of the software including – what information each part holds – what things each part can do – how the various.
Advertisements

CIT 590 Intro to Programming Classes. Schedule change The upcoming HW (HW6) is your last major Python HW. It will involve object oriented programming.
CSE115: Introduction to Computer Science I Dr. Carl Alphonce 219 Bell Hall
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 9 Classes.
Modules and Objects Introduction to Computing Science and Programming I.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 11 Classes and Object- Oriented Programming.
ECE122 L16: Class Relationships April 3, 2007 ECE 122 Engineering Problem Solving with Java Lecture 16 Class Relationships.
Lecture 05 – Classes.  A class provides the definition for the type of an object  Classes can store information in variables  Classes can provide methods.
Computer Science 111 Fundamentals of Programming I Introduction to Programmer-Defined Classes.
REFERENCES: CHAPTER 8 Object-Oriented Programming (OOP) in Python.
CS61A Lecture 2 Functions and Applicative Model of Computation Tom Magrino and Jon Kotker UC Berkeley EECS June 19, 2012.
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.
Chapter 10 Classes. Review of basic OOP concepts  Objects: comprised of associated DATA and ACTIONS (methods) which manipulate that data.  Instance:
Writing Classes (Chapter 4)
CIT 590 Intro to Programming Style Classes. Remember to finish up findAllCISCourses.py.
Chapter 11 Introduction to Classes Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new.
Introduction to Programming with Java. Overview What are the tools we are using – What is Java? This is the language that you use to write your program.
Computer Science 111 Fundamentals of Programming I More Data Modeling.
Constructing Objects Lab. Log into Wiley Plus Read the problem Write a BankAccountTester class whose main method constructs a bank account, deposits.
Guide to Programming with Python
Classes and Objects The basics. Object-oriented programming Python is an object-oriented programming language, which means that it provides features that.
Computer Science 112 Fundamentals of Programming II Interfaces and Implementations.
Functions. Built-in functions You’ve used several functions already >>> len("ATGGTCA")‏ 7 >>> abs(-6)‏ 6 >>> float("3.1415")‏ >>>
1 Programming for Engineers in Python Autumn Lecture 6: More Object Oriented Programming.
Classes COMPSCI 105 SS 2015 Principles of Computer Science.
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
Guide to Programming with Python Chapter Eight (Part I) Object Oriented Programming; Classes, constructors, attributes, and methods.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
72 4/11/98 CSE 143 Abstract Data Types [Sections , ]
Object-Oriented Programming (OOP) in Python References: Chapter 8.
CSC 1010 Programming for All Lecture 5 Functions Some material based on material from Marty Stepp, Instructor, University of Washington.
CSC 231: Introduction to Data Structures Python and Objects – Day 3 Dr. Curry Guinn.
Introduction to Computing Science and Programming I
Guide to Programming with Python
Object Oriented Programming
Adapted from slides by Marty Stepp and Stuart Reges
COMPSCI 107 Computer Science Fundamentals
Python Let’s get started!.
CSSE 120—Rose Hulman Institute of Technology
Topics Procedural and Object-Oriented Programming Classes
Copyright (c) 2017 by Dr. E. Horvath
Chapter 5 Black Jack.
Fundamentals of Programming II Interfaces and Implementations
Variables, Expressions, and IO
Functions CIS 40 – Introduction to Programming in Python
Lecture 14 Writing Classes part 2 Richard Gesick.
Object Oriented Programming
Procedural Abstraction Object-Oriented Code
Methods The real power of an object-oriented programming language takes place when you start to manipulate objects. A method defines an action that allows.
To Get Started Paper sheet
Object Oriented Programming
Functions Inputs Output
Class Constructor Recall: we can give default values to instance variables of a class The “numberOfPlayers” variable from the “PlayerData” class before.
Lesson 2: Building Blocks of Programming
File Handling Programming Guides.
Lesson 16: Functions with Return Values
Passing Parameters by value
Object Oriented Programming in Python
Today’s topics UML Diagramming review of terms
Defining Classes and Methods
Fundamentals of Programming I Commonly Used Methods More Modeling
Objects (again) Professor Hugh C. Lauer CS-1004 — Introduction to Programming for Non-Majors (Slides include materials from Python Programming: An Introduction.
Recursion Taken from notes by Dr. Neil Moore
CISC101 Reminders All assignments are now posted.
Task 2 Implementation help
Defining Classes and Methods
A Level Computer Science Topic 6: Introducing OOP
Functions, Procedures, and Abstraction
Presentation transcript:

Python programming - Defining Classes Catapult — Rose Hulman Institute of Technology

We've been creating & using objects WIDTH = 400 HEIGHT = 50 REPEAT_COUNT = 20 PAUSE_LENGTH = 0.25 win = GraphWin(‘Giants Win!', WIDTH, HEIGHT) p = Point(WIDTH/2, HEIGHT/2) t = Text(p, ‘NY Giants—2012 Super Bowl Champs!') t.setStyle('bold') t.draw(win) nextColorIsRed = True t.setFill('blue') for i in range(REPEAT_COUNT): sleep(PAUSE_LENGTH) if nextColorIsRed: t.setFill('red') else: nextColorIsRed = not nextColorIsRed win.close()

Object Terminology Point x y … getX() getY() move(dx,dy) Objects are active data types They know stuff— instance variables They can do stuff— methods Objects are instances of some class Objects created by calling constructors UML class diagram: x y … Point getX() getY() move(dx,dy) Instance variables written here [Animate this slide to reveal by major bullets] On board: UML is Unified Modeling Language Draw together the UML class diagram for Line on the board Methods written here

Key Concept! A class is like an "object factory" Calling the constructor tells the classes to make a new object Parameters to constructor are like "factory options", used to set instance variables Or think of class like a "rubber stamp" Calling the constructor stamps out a new object shaped like the class Parameters to constructor "fill in the blanks". That is, they are used to set instance variables. This slide has two different analogies. Reveal and discuss each.

Example Consider: p = Point(200, 100) t = Text(p, 'Go Giants!') t p Point x _______ y _______ fill _______ outline _______ getX() … getY() … … Text anchor _______ text _______ getAnchor() … getText() … setText(text) setStyle(style) … Point x _______ y _______ fill _______ outline _______ getX() … getY() … … 200 100 'black' 200 100 'black' 'Go Giants' [Includes animated builds of objects] -Python stamps out a point object in memory, using the Point class as a template -Point's constructor fills in the slots, using parameters and default values -Python attaches the 'p' variable to the point object -Python stamps out a text object in memory, using the Text class as a template -Text's constructor fills in the slots… -…making a clone of the point object in the process (Why? So if we do p.move() the text stays put, and if we do t.move() the point stays put.) - …finishing Text object slots -Python attaches the 't' variable to the text object This is a clone of p

Creating Custom Objects: Defining Your Own Classes Hide complexity Provide another way to break problems into pieces You can define an object, like a “player” or a “square” Make it easier to pass information around Other people on your team can write code to use these! Develop together on board, class diagrams for Card, Deck. Steer them toward class diagram for Card that goes with code on the next slide. Can be more creative with Deck. Questions to ask: What data do we need to store inside a card object? (card name, suit) What kinds of operations do we need to do on a card? (print it, get its value for BlackJack)

Code to Define a Class Declares a class named Card class Card: """This class represents a card from a standard deck.""" docstring describes class, used by help() function and by Eclipse help Animate call-outs

Code to Define a Class A sample constructor call: Special name, __init__ declares a constructor class Card: """This class represents a card from a standard deck.""" def __init__(self, card, suit): self.cardName = card self.suitName = suit Special self parameter is the first formal parameter of each method in a class. self always refers to the current object Create instance variables just by assigning to them c Card def __init__(self,card,suit): self.cardName = card self.suitName = suit A sample constructor call: c = Card('Ace', 'Hearts') Animate call-outs. special name self parameter show calling code (multi-step animation of object creation and initialization) create instance variables just by assigning to them cardName ______ suitName ______ 'Ace' 'Hearts'

Code to Define a Class A sample method call: c.getValue() Card… class Card: """This class represents a card from a standard deck.""" def __init__(self, card, suit): self.cardName = card self.suitName = suit def getValue(self): """Returns the value of this card in BlackJack. Aces always count as one, so hands need to adjust to count aces as 11.""" pos = cardNames.index(self.cardName) if pos < 10: return pos + 1 return 10 self parameter again, no other formal parameters docstring for method Animate call-outs. add accessor: docstring again self argument again show calling code reading instance variable use self.<varName> to read instance variable A sample method call: c.getValue() Card…

Code to Define a Class Sample uses of __str__ method: print c class Card: """This class represents a card from a standard deck.""" def __init__(self, card, suit): self.cardName = card self.suitName = suit def getValue(self): """Returns the value of this card in BlackJack. Aces always count as one, so hands need to adjust to count aces as 11.""" pos = cardNames.index(self.cardName) if pos < 10: return pos + 1 return 10 def __str__(self): return self.cardName + " of " + self.suitName Sample uses of __str__ method: print c msg = "Card is " + str(c) Animate call-outs. add __str__: another special name Ask what the self.cardName and self.suitName expressions do. (read instance variable values) show calling code, both `print card` and "First card is " + str(card) Special __str__ method returns a string representation of an object

Stepping Through Some Code Sample use: card = Card('7','Clubs') print card.getValue() print card class Card: """This class represents a card from a standard deck.""" def __init__(self, card, suit): self.cardName = card self.suitName = suit def getValue(self): """Returns the value of this card in BlackJack. Aces always count as one, so hands need to adjust to count aces as 11.""" pos = cardNames.index(self.cardName) if pos < 10: return pos + 1 return 10 def __str__(self): return self.cardName + " of " + self.suitName Add the given code to the end of backjackWithClasses (in EclipseProjects/BallSim Eclipse project, because we give it to students as a reference for writing ballSim) Comment out the call to main(), step through the code using "Step Into" and showing: self in the debugger as we step into the constructor, note that the instance variables aren't there step through the constructor, see instance variables appear step into getValue, show values of instance variables inside self step into the print statement, show that control jumps to the special __str__ method Also while in Eclipse, show how the docstrings show up by putting the insertion point after a constructor call to Card and hitting control-space.

Key Ideas Constructor: Instance variables: self formal parameter: Defined with special name __init__ Called like ClassName() Instance variables: Created when we assign to them Live as long as the object lives self formal parameter: Implicitly get the value before the dot in the call Allows method of an object to "talk about itself"

Let's write some code! A fraction object: A bank account object: Knows its numerator and denominator Can do math with it (add, etc) to another fraction Can print itself intelligently A bank account object: Knows it balance Can tell you its balance Can accept a deposit Can provide a withdrawal

You’re using classes already… In Tic Tac Toe, to define “Square”. One more game we’ll try – “Moving Smileys” – has a few more of these!