Week 2. Classes and Objects

Similar documents
Exceptions. raise type(message) raise Exception(message)

Exceptions. raise type(message) raise Exception(message)

CSc 110, Autumn Lecture 30: Methods. Adapted from slides by Marty Stepp and Stuart Reges

Fundamentals of Programming (Python) Object-Oriented Programming. Ali Taheri Sharif University of Technology Spring 2018

OBJECT ORIENTED PROGRAMMING

Building Java Programs

Lecture 38: Python. CS 51G Spring 2018 Kim Bruce

Class Design (Section 9 of 17)

1 Classes. 2 Exceptions. 3 Using Other Code. 4 Problems. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, / 19

Lecture 19: Subclasses & Inheritance (Chapter 18)

Lessons on Python Classes and Objects

CIS192 Python Programming

CIS192 Python Programming

Week 2. expressions, variables, for loops

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

COMPSCI 105 S Principles of Computer Science. Classes 3

Lecture 18. Classes and Types

Programming I. Course 9 Introduction to programming

Lecture 21. Programming with Subclasses

Computational Physics

PREPARING FOR PRELIM 2

CS 11 python track: lecture 4

Lecture 21. Programming with Subclasses

Python Development with PyDev and Eclipse -

Lecture 21. Programming with Subclasses

Lecture 18. Methods and Operations

CSC148-Section:L0301

Python for Finance. Advanced Features. Andras Niedermayer

Object Oriented Programming #10

ECE 364 Software Engineering Tools Laboratory. Lecture 7 Python: Object Oriented Programming

Have classes that describe the format of objects. Create objects by stating the class of the object to be created.

CS 112 Introduction to Programming

CSE115 / CSE503 Introduction to Computer Science I. Dr. Carl Alphonce 343 Davis Hall Office hours:

Review 2. Classes and Subclasses

Object Oriented Programming

CSC148-Section:L0301

Today. CSE341: Programming Languages. Late Binding in Ruby Multiple Inheritance, Interfaces, Mixins. Ruby instance variables and methods

Python A Technical Introduction. James Heliotis Rochester Institute of Technology December, 2009

PREPARING FOR THE FINAL EXAM

Scientific Programming. Lecture A09 Programming Paradigms

Programming Languages

Object-oriented programming in Python (2)

Building Java Programs

MACS 261J Final Exam. Question: Total Points: Score:

Object Oriented Programming

COMP519 Web Programming Lecture 21: Python (Part 5) Handouts

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Admin. CS 112 Introduction to Programming. Exercise: Gene Finding. Language Organizing Structure. Gene Finding. Foundational Programming Concepts

CS558 Programming Languages Winter 2013 Lecture 8

CSE341: Programming Languages Lecture 23 Multiple Inheritance, Mixins, Interfaces, Abstract Methods. Dan Grossman Autumn 2018

Lecture 11: Intro to Classes

Advanced Python. Executive Summary, Session 1

CSC102 INTRO TO PROGRAMMING WITH PYTHON LECTURE 22 CLASS MICHAEL GROSSBERG

Inheritance and Polymorphism

Iterators & Generators

Object Oriented Programming in Python 3

TeenCoder : Java Programming (ISBN )

CSC148 Intro. to Computer Science

Object-Oriented Python

Object Model Comparisons

STSCI Python Introduction

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Classes and Objects 1 / 13

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

20. More Complicated Classes. A Class For Manipulating Fractions. A Class For Manipulating Fractions 4/19/2016. Let s Define a Class to Do This Stuff

Admin. CS 112 Introduction to Programming. Recap: OOP Analysis. Software Design and Reuse. Recap: OOP Analysis. Inheritance

CompuScholar, Inc. 9th - 12th grades

Computer Science II (20073) Week 1: Review and Inheritance

Object-Oriented Programming (OOP) Basics. CSCI 161 Introduction to Programming I

Operator Overloading. a flop = a floating-point operation overloading arithmetical operators counting number of flops in a sum

What is Inheritance?

CSE : Python Programming

PREPARING FOR THE FINAL EXAM

Week 8 Lecture: Programming

Review 3. Exceptions and Try-Except Blocks

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

A Java program contains at least one class definition.

Class extension and. Exception handling. Genome 559

Recall. Key terms. Review. Encapsulation (by getters, setters, properties) OOP Features. CSC148 Intro. to Computer Science

Python for Astronomers. Errors and Exceptions

Building Java Programs

Absent: Lecture 3 Page 1. def foo(a, b): a = 5 b[0] = 99

Data Structures (list, dictionary, tuples, sets, strings)

Inheritance and Interfaces

Programming in Python

Topic 7: Algebraic Data Types

mith College Computer Science Week 13 CSC111 Fall 2015 (Lab 12, Homework 12) Dominique Thiébaut

Python OOP. Stéphane Vialette. LIGM, Université Paris-Est Marne-la-Vallée. October 19, 2010

Class extension and. Exception handling. Genome 559

Object Oriented Programming: Based on slides from Skrien Chapter 2

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

Francesco Nidito. Programmazione Avanzata AA 2007/08

Francesco Nidito. Programmazione Avanzata AA 2007/08

Programming Exercise 14: Inheritance and Polymorphism

JAVA MOCK TEST JAVA MOCK TEST II

Overview. Recap of FP Classes Instances Inheritance Exceptions

Python. Executive Summary

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

CS260 Intro to Java & Android 03.Java Language Basics

Computational Mathematics with Python

Transcription:

Week 2 Classes and Objects Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this work is licensed under: http://creativecommons.org/licenses/by-nc-sa/3.0

OOP and Python Python was built as a procedural language OOP exists and works fine, but feels a bit more "tacked on" Java probably does classes better than Python (gasp) 2

Defining a Class Declaring a class: class Name:... class name is capitalized (e.g. Point) saved into a file named name.py (filename is lowercase) 3

Fields Declaring a field: name = value Example: class Point: x = 0 y = 0 2 3 point.py class Point: x = 0 y = 0 4

Using a Class from name import * client programs must import the classes they use the file name (lowercase), not class name, is used point_main.py 2 3 4 5 6 7 8 from point import * # main p = Point() p.x = 7 p.y = -3... 5

"Implicit" Parameter (self) Java object methods refer to the object's fields implicitly: public void translate(int dx, int dy) { x += dx; y += dy; // change this object's x/y } Python's implicit parameter is named self self must be the first parameter of any object method access the object's fields as self.field def translate(self, dx, dy): self.x += dx self.y += dy 6

Methods def name(self [, parameter,..., parameter]): statements Example: class Point: def translate(self, dx, dy): self.x += dx self.y += dy... Exercise: Write the following methods in class Point: set_location draw distance 7

Exercise Answer point.py 2 3 4 5 6 7 8 9 0 2 3 4 5 6 7 8 9 20 from math import * class Point: x = 0 y = 0 def set_location(self, x, y): self.x = x self.y = y def draw(self, panel): panel.canvas.create_oval(self.x, self.y, \ self.x + 3, self.y + 3) panel.canvas.create_text(self.x, self.y, \ text=str(self), anchor="sw") def distance(self, other): dx = self.x - other.x dy = self.y - other.y return sqrt(dx * dx + dy * dy) 8

Initializing Objects Right now, clients must initialize Points like this: p = Point() p.x = 3 p.y = -5 We'd prefer to be able to say: p = Point(3, -5) 9

Constructors def init (self [, parameter,..., parameter]): statements a constructor is a special method with the name init that initializes the state of an object Example: class Point: def init (self, x, y): self.x = x self.y = y 0

More About Fields point.py 2 3 4 5 class Point: def init (self, x, y): self.x = x self.y = y... >>> p = Point(5, -2) >>> p.x 5 >>> p.y -2 fields can be declared directly inside class, or just in the constructor as shown here (more common)

Printing Objects By default, Python doesn't know how to print an object: >>> p = Point(5, -2) >>> print p <Point instance at 0x00A8A850> We'd like to be able to print a Point object and have its state shown as the output. 2

Printable Objects: str def str (self): return string converts an object into a string (like Java tostring method) invoked automatically when str or print is called def str (self): return "(" + str(self.x) + ", " + str(self.y) + ")" >>> p = Point(5, -2) >>> print p (5, -2) >>> print "The point is " + str(p) + "!" The point is (5, -2)! 3

Complete Point Class point.py 2 3 4 5 6 7 8 9 0 2 3 4 5 6 7 8 9 20 2 from math import * class Point: def init (self, x, y): self.x = x self.y = y def distance_from_origin(self): return sqrt(self.x * self.x + self.y * self.y) def distance(self, other): dx = self.x - other.x dy = self.y - other.y return sqrt(dx * dx + dy * dy) def translate(self, dx, dy): self.x += dx self.y += dy def str (self): return "(" + str(self.x) + ", " + str(self.y) + ")" 4

Python Object Details Drawbacks Does not have encapsulation like Java (ability to protect fields' data from access by client code) Not easy to have a class with multiple constructors Must explicitly declare self parameter in all methods Strange names like str, init Benefits operator overloading: Define < by writing lt, etc. http://docs.python.org/ref/customization.html 5

Exceptions raise type(message) raise Exception(message) Exceptions AssertionError TypeError NameError ValueError IndexError SyntaxError ArithmeticError http://docs.python.org/library/exceptions.html#bltin-exceptions 6

Class Syntax Recall the syntax for making a basic class example.py 2 3 4 5 6 7 8 9 class ClassName: def init (self, params,...): self.field = value self.fieldn = value #Your code here def other_methods(self, params,...): #your code here 7

Inheritance Python has multiple inheritance This means that we can create a class that subclasses several classes Python makes an effort to mix super classes Searches super classes from left to right We can disambiguate if there are problems with this example.py 2 class ClassName(SuperClass, SuperClass2,...): def init (self, params,...): 8

Commenting Your Classes Classes and functions have a built-in field called doc We can use this as a way to get more bang for our comments These doc fields could be used like JavaDoc example.py 2 3 4 class Point(): This class defines a point in 2D space def init (self, x, y): Post: returns a Point with the given x and y fields 9

Name Mangling Python does not have private methods Python does have name mangling, any method that starts with 2+ underscores and does not end in 2+ underscores with be renamed to _classname method example.py 2 3 4 5 6 7 8 9 class Foo(): def init (self): self. helper() def helper(self): print( sneaky ) x = Foo() x._foo helper() x. helper() #output: sneaky #output: sneaky #output: AttributeError 20

Static Fields There is a subtle difference between declaring fields in the class and declaring them in the constructor Fields defined in the class can be used as static variables, meaning they belong to the class as a whole example.py 2 3 4 5 6 7 class MovieTicket(): baseprice = 0 def init (self, fee): self.price = self.baseprice + fee x = MovieTicket(5) print(x.price) #result: 5 print(movieticket.baseprice) #result: 0 2

Static Methods We can use decorators to tell our function to be static, meaning they belong to the class, not an instance example.py 2 3 4 5 6 7 8 9 0 class Point(): def init (self, x, y): self.x = x self.y = y @staticmethod def distance(p, p2): d = sqrt((p.x - p2.x)**2 + (p.y - p2.y)**2 ) return d x = Point(0, 0) y = Point(0, 5) print(point.distance(x, y)) #result: 5 22

Class Methods A class method receives a reference to the class instead of a reference to an instance You can use this class parameter (cls) to reference the static variables or methods One use of this ability is writing documentation methods 23

Class Methods A class method receives a reference to the class instead of a reference to an instance You can use this class parameter (cls) to reference the static variables or methods One use of this ability is writing documentation methods 24

Class Methods example.py 2 3 4 5 6 7 8 9 0 2 3 4 class Point(): """This class defines a point in 2D space.""" def init (self, x, y): """Post: returns a Point with coordinates (x,y)""" self.x = x self.y = y @classmethod def help(cls): for attr in cls. dict : print(str(attr) + ": " + cls. dict [attr]. doc )#result: 5 x = Point(0, 0) x.help() 25

str () We already know about the str () method that allows a class to convert itself into a string rectangle.py 2 3 4 5 6 7 8 9 class Point: def init (self, x, y): self.x = x self.y = y def str (self): return "(" + str(self.x) + ", " + str(self.y) + ")" 26

First Class Citizens For built-in types like ints and strings we can use operators like + and *. Our classes so far were forced to take back routes and use methods like add() or remove() Python is super cool, in that it allows us to define the usual operators for our class This brings our classes up to first class citizen status just like the built in ones 27

Underscored methods There are many other underscored methods that allow the built-in function of python to work Most of the time the underscored name matches the built-in function name Built-In str() len() abs() Class Method str () len () abs () 28

Underscored methods There are underscore methods that you can implement in order to define logical operations and arithmetic operations Binary Operators Comparison Operators Operator Class Method - sub (self,other) + add (self, other) * mul (self, other) / truediv (self, other) Unary Operators Operator Class Method - neg (self) + pos (self) Operator Class Method == eq (self,other)!= ne (self, other) < lt (self, other) > gt (self, other) <= le (self, other) >= ge (self, other) N/A nonzero (self) http://docs.python.org/reference/datamodel.html#sequence-types 29

Vector Class Lets write a class that represents a Vector. A Vector is a Point that has some extra functionality. We should be able to add and subtract two Vectors, determine if two Vectors are equal. We should be able to multiply a Vector by a scalar and ask what the Vector s length is as an integer. In addition, Vectors should have these methods and fields. Method/Field origin isdiagonalinpointset() slope() Functionality The origin as a field Returns whether this Vector lies on the diagonal and is contained in the given point set Returns the slope between the two given Vectors 30