Classes Special thanks to Roy McElmurry, Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this.

Slides:



Advertisements
Similar presentations
Optional Static Typing Guido van Rossum (with Paul Prescod, Greg Stein, and the types-SIG)
Advertisements

Exception Handling Genome 559. Review - classes 1) Class constructors - class myClass: def __init__(self, arg1, arg2): self.var1 = arg1 self.var2 = arg2.
Object-Oriented Programming
Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
Programmer-defined classes Part 2. Topics Returning objects from methods The this keyword Overloading methods Class methods Packaging classes Javadoc.
Week 2 Classes, Objects and lists review Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise.
Week 5 while loops; logic; random numbers; tuples Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except.
Week 2 expressions, variables, for loops Special thanks to Scott Shawcroft, Ryan Tucker, Paul Beck, Hélène Martin, Kim Todd, John Kurkowski, and Marty.
Unit 8 Classes and Objects; Inheritance Special thanks to Roy McElmurry, John Kurkowski, Scott Shawcroft, Ryan Tucker, Paul Beck for their work. Except.
Floating point numbers in Python Floats in Python are platform dependent, but usually equivalent to an IEEE bit C “double” However, because the significand.
COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris
Unit 5 while loops; logic; random numbers; tuples Special thanks to Roy McElmurry, John Kurkowski, Scott Shawcroft, Ryan Tucker, Paul Beck for their work.
Python Programming Chapter 14: Classes and Methods Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
11/27/07. >>> Overview * objects * class * self * in-object methods * nice printing * privacy * property * static vs. dynamic * inheritance.
Object-oriented Programming (review + a few new tidbits) "Python Programming for the Absolute Beginner, 3 rd ed." Chapters 8 & 9 Python 3.2 reference.
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.
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
Introduction to Pyrex September 2002 Brian Quinlan
Classes CS 21a: Introduction to Computing I First Semester,
Operators in Python. Arithmetic operators Some operators in Python will look familiar (+, -, *, /) Others are new to you (%, //, **) All of these do work.
Classes 1 COMPSCI 105 S Principles of Computer Science.
Iterators, Linked Lists, MapReduce, Dictionaries, and List Comprehensions... OH MY! Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their.
Unit 2 Expressions and variables; for loops Special thanks to Roy McElmurry, John Kurkowski, Scott Shawcroft, Ryan Tucker, Paul Beck for their work. Except.
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.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
Inheritance (Part 5) Odds and ends 1. Static Methods and Inheritance  there is a significant difference between calling a static method and calling a.
Week 2 expressions, variables, for loops Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise.
Week 2 expressions, variables, for loops Special thanks to Scott Shawcroft, Ryan Tucker, Paul Beck, Hélène Martin, Kim Todd, John Kurkowski, and Marty.
C# Operator Overloading and Type Conversions C#.NET Software Development Version 1.0.
Classes COMPSCI 105 SS 2015 Principles of Computer Science.
CS305j Introduction to Computing Classes II 1 Topic 24 Classes Part II "Object-oriented programming as it emerged in Simula 67 allows software structure.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Lecture 09 – Classes.  At the end of this lecture, students should be able to:  Define a new class  Store state information about instances of the.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 8: Classes and Objects.
CS2102: Lecture on Abstract Classes and Inheritance Kathi Fisler.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Rapid GUI Programming with Python and Qt Classes and Modules By Raed S. Rasheed Classes and Modules By Raed S. Rasheed 1.
Built-In Functions Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this work.
ITI 1120 Lab #10 Objects and Classes Slides by: Romelia Plesa, Sylvia Boyd, Alan Williams, Diana InkPen, Daniel Amyot, Gilbert Arbez, Mohamad Eid.
Adapted from slides by Marty Stepp and Stuart Reges
More Sophisticated Behavior
Adapted from slides by Marty Stepp and Stuart Reges
Classes and Objects; Inheritance
Classes and Objects – digging deeper
COMPSCI 107 Computer Science Fundamentals
Week 8 Classes and Objects
Mathematical operators overload
CS-104 Final Exam Review Victor Norman.
Variables, Expressions, and IO
Python Classes By Craig Pennell.
CHAPTER FIVE Classes.
CS2102: Lecture on Abstract Classes and Inheritance
Adapted from slides by Marty Stepp and Stuart Reges
Inherited Classes in Java
Programmazione ad alto livello con Python
Week 8 Classes and Objects
Adapted from slides by Marty Stepp and Stuart Reges
Classes Special thanks to Roy McElmurry, Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this.
expressions, variables, for loops
expressions, variables, for loops
while loops; logic; random numbers; tuples
Built-In Functions Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this work.
Classes, Objects and lists
CISC/CMPE320 - Prof. McLeod
Access control Many languages have a notion of 'private' variables that can't be accessed from outside an object. For example, if we were sending someone.
CSE 142 Lecture Notes Defining New Types of Objects, cont'd.
Functional Programming
Week 2 Classes and Objects
Presentation transcript:

Classes Special thanks to Roy McElmurry, Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this work is licensed under:

2 Exceptions raise type(message) raise Exception(message) Exceptions AssertionError TypeError NameError ValueError IndexError SyntaxError ArithmeticError

3 Class Syntax Recall the syntax for making a basic class example.py class ClassName: def __init__(self, params,...): self.field1 = value self.fieldn = value #Your code here def other_methods(self, params,...): #your code here

4 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 1212 class ClassName(SuperClass1, SuperClass2,...): def __init__(self, params,...):

5 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 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”””

6 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 class Foo(): def __init__(self): self.__helper() def __helper(self): print(“sneaky”) x = Foo() #output: sneaky x._Foo__helper() #output: sneaky x.__helper() #output: AttributeError

7 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 class MovieTicket(): basePrice = 10 def __init__(self, fee): self.price = self.basePrice + fee x = MovieTicket(5) print(x.price) #result: 15 print(MovieTicket.basePrice) #result: 10

8 Static Methods We can use decorators to tell our function to be static, meaning they belong to the class, not an instance example.py class Point(): def __init__(self, x, y): self.x = x self.y = def distance(p1, p2): d = sqrt((p1.x - p2.x)**2 + (p1.y - p2.y)**2 ) return d x = Point(0, 0) y = Point(0, 5) print(Point.distance(x, y)) #result: 5

9 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

10 Class Methods example.py 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 = def help(cls): for attr in cls.__dict__: print(str(attr) + ": " + cls.__dict__ [attr].__doc__)#result: 5 x = Point(0, 0) x.help()

11 __str__() We already know about the __str__() method that allows a class to convert itself into a string rectangle.py class Point: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return "(" + str(self.x) + ", " + str(self.y) + ")"

12 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

13 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-InClass Method str()__str__() len()__len__() abs()__abs__()

14 Underscored methods There are underscore methods that you can implement in order to define logical operations and arithmetic operations OperatorClass Method - __sub__(self,other) + __add__(self, other) * __mul__(self, other) / __truediv__(self, other) Binary OperatorsComparison Operators Unary Operators OperatorClass Method - __neg__(self) + __pos__(self) OperatorClass Method == __eq__(self,other) != __ne__(self, other) < __lt__(self, other) > __gt__(self, other) <= __le__(self, other) >= __ge__(self, other) N/A __nonzero__(self)

15 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/FieldFunctionality originThe origin as a field isDiagonalInPointSet()Returns whether this Vector lies on the diagonal and is contained in the given point set slope()Returns the slope between the two given Vectors