Q and A for Sections 6.2, 6.3 Victor Norman CS106.

Slides:



Advertisements
Similar presentations
ThinkPython Ch. 10 CS104 Students o CS104 n Prof. Norman.
Advertisements

CATHERINE AND ANNIE Python: Part 3. Intro to Loops Do you remember in Alice when you could use a loop to make a character perform an action multiple times?
Python Objects and Classes
Python Mini-Course University of Oklahoma Department of Psychology Lesson 28 Classes and Methods 6/17/09 Python Mini-Course: Lesson 28 1.
Chapter 6 Lists and Dictionaries CSC1310 Fall 2009.
Q and A for Chapter 6 CS 104 Victor Norman. Return values Q: A function definition that returns a value (i.e., a non-void function) must have at least.
Classes 2 COMPSCI 105 SS 2015 Principles of Computer Science.
Rapid GUI Programming with Python and Qt Classes and Modules By Raed S. Rasheed Classes and Modules By Raed S. Rasheed 1.
ECE 103 Engineering Programming Chapter 11 One Minute Synopsis Herbert G. Mayer, PSU CS Status 7/1/2014.
Chapter 9 Imperative and object-oriented languages 1.
Object-Oriented Programming in Python Goldwasser and Letscher Chapter 6 Defining Our Own Classes Terry Scott University of Northern Colorado 2007 Prentice.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Introduction to ML - Part 2 Kenny Zhu. What is next? ML has a rich set of structured values Tuples: (17, true, “stuff”) Records: {name = “george”, age.
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
Loops We have been using loops since week 2, our void draw(){ } is a loop A few drawbacks of draw() –It is endless –There is only one draw() –It updates.
CS 117 Spring 2002 Review for Exam 3 arrays strings files classes.
Classes and Objects, Part 1 Victor Norman CS104. Reading Quiz, Q1 A class definition define these two elements. A. attributes and functions B. attributes.
Floating point numbers in Python Floats in Python are platform dependent, but usually equivalent to an IEEE bit C “double” However, because the significand.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
Classes 3 COMPSCI 105 S Principles of Computer Science.
Lists in Python.
CSC1018F: Object Orientation, Exceptions and File Handling Diving into Python Ch. 5&6 Think Like a Comp. Scientist Ch
Multi-Dimensional Arrays
Introduction. 2COMPSCI Computer Science Fundamentals.
Characters The data type char represents a single character in Java. –Character values are written as a symbol: ‘a’, ‘)’, ‘%’, ‘A’, etc. –A char value.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
More On Classes UW CSE 160 Spring Classes define objects What are objects we've seen? 2.
Built-in Data Structures in Python An Introduction.
Q and A for Sections 2.9, 4.1 Victor Norman CS106 Fall 2015.
Functions. Built-in functions You’ve used several functions already >>> len("ATGGTCA")‏ 7 >>> abs(-6)‏ 6 >>> float("3.1415")‏ >>>
Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 8 Lists and Tuples.
Overview The Basics – Python classes and objects Procedural vs OO Programming Entity modelling Operations / methods Program flow OOP Concepts and user-defined.
1 Programming for Engineers in Python Autumn Lecture 6: More Object Oriented Programming.
WEEK 6 Class Activities Lecturer’s slides.
Extra Stuff for CS106 Victor Norman CS106. break and continue break and continue are both ways to alter the flow of a loop Can be used only inside a loop.
Object Oriented Programing (OOP)
Q and A for Sections – CS 106 Victor Norman Calvin College.
Classes COMPSCI 105 SS 2015 Principles of Computer Science.
Last Week Modules Save functions to a file, e.g., filename.py The file filename.py is a module We can use the functions in filename.py by importing it.
CS Class 19 Today  Practice with classes Announcements  Turn in algorithm for Project 5 in class today  Project 5 due 11/11 by midnight – .
1 Arrays of Arrays An array can represent a collection of any type of object - including other arrays! The world is filled with examples Monthly magazine:
Classes and Objects, Part 1 Victor Norman CS104. “Records” In Excel, you can create rows that represent individual things, with each column representing.
Chapter 17 Q and A Victor Norman, et al. CS104. What is Object-oriented Programming? Q: What is object-oriented programming? A: It means defining classes/objects,
SEQUENCES:STRINGS,LISTS AND TUPLES. SEQUENCES Are items that are ordered sequentially and accessible via index offsets into its set of elements. Examples:
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
LISTS and TUPLES. Topics Sequences Introduction to Lists List Slicing Finding Items in Lists with the in Operator List Methods and Useful Built-in Functions.
Two Dimensional Arrays. Students will be able to: code algorithms to solve two- dimensional array problems. use 2-D arrays in programs. pass two-use 2-D.
Arrays What is an array… –A data structure that holds a set of homogenous elements (of the same type) –Associate a set of numbers with a single variable.
SEQUENCES:STRINGS,LISTS AND TUPLES. SEQUENCES Are items that are ordered sequentially and accessible via index offsets into its set of elements. Examples:
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 this week – last section on Friday. Assignment 4 is posted. Data mining: –Designing functions.
Lists/Dictionaries. What we are covering Data structure basics Lists Dictionaries Json.
Beginning C for Engineers Fall 2005 Arrays, 2-D arrays, character strings Bettina Schimanski Lecture 5: Section 2 (9/28/05) Section 4 (9/29/05)
Indentations makes the scope/block Function definition def print_message (): print “hello” Function usages print_message () hubo.move ()// hubo is a class.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Strings C supports strings using one-dimensional character arrays. A string is defined as a null-terminated character array. In C, a null is 0. You must.
Operator Overloading Introduction
Types CSCE 314 Spring 2016.
More On Classes UW CSE 160 Winter
Classes and Objects – digging deeper
COMPSCI 107 Computer Science Fundamentals
Mathematical operators overload
CS-104 Final Exam Review Victor Norman.
Introduction to Python
8 – Lists and tuples John R. Woodward.
Topics Sequences Introduction to Lists List Slicing
Topics Sequences Introduction to Lists List Slicing
Terry Scott University of Northern Colorado 2007 Prentice Hall
Data Types Every variable has a given data type. The most common data types are: String - Text made up of numbers, letters and characters. Integer - Whole.
Presentation transcript:

Q and A for Sections 6.2, 6.3 Victor Norman CS106

Parameterized Constructor Q: Can you create multiple constructors for a class, so that you can create new objects in different ways? A: No. You can have only 1 __init__ definition. But you can use optional parameters to allow the caller to create objects in multiple ways. Remember: in general, a constructor should initialize all its member attributes to values.

Example class Card: def __init__(self, num=2, suit=“H”): “””Create new card. If num and suit are not specified, it is a 2 of hearts.””” self._num = num self._suit = suit card = Card() # 2 of hearts card2 = Card(11, “S”) # jack of spades

Exercise Given this definition, write the accessor and mutator methods. class Car: def __init__(self, numWheels=4, color=“black”): self._numWh = numWheels self._color = color

How does __str__ get called? Special methods get called by the python interpreter when they are defined in a class. e.g., __str__(), if defined, is called by python whenever the object must be converted to a string – like when str(obj) is called or print obj is called. in other words: the python interpret sees this: print obj. – It looks up the class of obj, and checks if __str__ has been defined for it. If so, it calls it to get the string representation for it. Otherwise, it calls a built-in way to convert it – usually resulting in something like

What other special methods are there? del.html del.html Especially useful: __cmp__(self, other): compare two objects __contains__(self, item): called when in is used __add__, __sub__, __mul__, etc.: x + y  x.__add__(y), based on x’s type.

Which special methods must we know? __init__ __str__ __cmp__ (others, like __add__, are occasionally useful…) NOTE NOTE NOTE: do *not* define your own methods with __ before and after.

Polymorphism Means: operators/functions (like +, -, abs(), len(), in, and, +=, %) may behave completely differently, based on the types of their operands. Also known as “operator overloading” “Josh ” + “Bulten”  concatenation  addition [‘Go’] + [‘Calvin’]  append

jumpPrevChannel() code Television class has two attributes: _channel, _prevChan. Wrong: self._channel = self._prevChan self._prevChan = self._channel Need to swap values: easiest with tuple assignment: self._channel, self._prevChan = self._prevChan, self._channel

isinstance() returns boolean Very useful for checking types of input parameters to a function/method isinstance(object, (tuple, of, types))  boolean if not isinstance(param, (int, float)): print “Illegal parameter!” (We’ll learn how to handle this better next week, with exceptions.)

Objects that reference other objects Very common to have multiple classes, and objects in one class reference other classes. E.g.: deck object has a list of card objects. – Always want to store objects – not, e.g., string representations of objects. Important to get the methods in the correct classes.

Calling methods from methods Q: Is calling a method within a method definition similar to calling a function from within another function? A: Yes and no. Yes: control is transferred to the method and returned back when the method completes. No: you have to use self.calledMethod() to do the call.

Example class Hand: def __init__(self, ……): … def isStraight(self): … def isFlush(self): … def isStraightFlush(self): ‘’’return True if this hand is a straight flush, False otherwise.’’’ return self.isFlush() and self.isStraight()

Two-dimensional arrays/lists Often in modeling the world, we need to use two-dimensional arrays of “cells”. We can model many different things with 2d arrays: – landscapes – petri dishes – mini-world – matrix store as a list of lists.

2D lists Like putting turtles on the screen, the 2d array has a width and height. Typically x is horiz, y is vertical. Often (0, 0) is upper-left corner. If world is your 2d list, then we access by world[x][y] x is column index, y is row index (or, y is the item in the y-th row in the x-th column) world[x] is a column.

Initializing a 2D list (list of lists) Want MAXCOLS columns and MAXROWS rows, each holding subsequent integers from 0. – for 3x4 array: world = [ [0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11] ] MAXROWS = 3 MAXCOLS = 4 world = [] for x in range(MAXCOLS): # create MAXCOLS lists world.append([]) val = 0 for col in world: # add MAXROWS items to each column for y in range(MAXROWS): col.append(val) val += 1

Exercise: average neighbors Write code to find the sum of 4 neighbors of cell at x, y, assuming cell is not on an edge. sum = world[x-1][y] + world[x+1][y] + world[x][y-1] + world[x][y+1]

Example: Teams, Players Write a class definition for a Player class. Each Player object has these attributes: _name _number _age _position _salary _team Write the constructor definition.

Continued Write a class definition for a Team. Each Team object contains _name _players addPlayer () delPlayer () getTotalSalary () Write the constructor (setting name and players). Write addPlayer ().

Continued Want to be able to print out this for a player: Peyton Manning, #18, QB, Denver Write the code to do this.

Continued Write the code for getTotalSalary () in Team.