methods and operations announcements for this lecture
play

Methods and Operations Announcements for This Lecture Assignments - PowerPoint PPT Presentation

Lecture 18 Methods and Operations Announcements for This Lecture Assignments Lab this Week Simple class exercise A4 Due Thursday at midnight Fill in predefined methods Hopefully you are on Task 4 Setting you up for


  1. Lecture 18 Methods and Operations

  2. Announcements for This Lecture Assignments Lab this Week • Simple class exercise • A4 Due Thursday at midnight § Fill in predefined methods § Hopefully you are on Task 4 § Setting you up for A6… § Extra consultants available • Will post A5 on Thursday Exams § Written assignment like A2 § Needs material from next Tues • Moved to handback room § Located in Gates 216 • Will also post A6 as well § Open 12-4:30 daily § Not due until November 19 • Regrades still open this week § Want to avoid exam crunch 10/27/15 Methods and Operations 2

  3. Important! YES NO class Point3(object): class Point3: """Instances are 3D points """Instances are 3D points Attributes: Attributes: x: x-coord [float] x: x-coord [float] y: y-coord [float] y: y-coord [float] z: z-coord [float]""" z: z-coord [float]""" … … 3.0-Style Classes “Old-Style” Classes Well-Designed Very, Very Bad 10/27/15 Methods and Operations 3

  4. Case Study: Fractions class Fraction(object): • Want to add a new type """Instance is a fraction n/d § Values are fractions: ½ , ¾ Attributes: § Operations are standard numerator: top [int] multiply, divide, etc. denominator: bottom [int > 0] § Example : ½ * ¾ = ⅜ """ • Can do this with a class def __init__(self,n=0,d=1): § Values are fraction objects """Init: makes a Fraction""" § Operations are methods self.numerator = n self.denominator = d • Example : simplefrac.py 10/27/15 Methods and Operations 4

  5. Problem: Doing Math is Unwieldy What We Want What We Get 1 2 + 1 3 + 1 4 ∗ 5 >>> p = Fraction(1,2) >>> q = Fraction(1,3) 4 >>> r = Fraction(1,4) >>> s = Fraction(5,4) >>> (p.add(q.add(r))).mult(s) This is confusing! 10/27/15 Methods and Operations 5

  6. Problem: Doing Math is Unwieldy What We Want What We Get 1 2 + 1 3 + 1 4 ∗ 5 >>> p = Fraction(1,2) >>> q = Fraction(1,3) 4 >>> r = Fraction(1,4) >>> s = Fraction(5,4) Why not use the >>> (p.add(q.add(r))).mult(s) standard Python math operations? This is confusing! 10/27/15 Methods and Operations 6

  7. Recall: The __init__ Method two underscores w = Worker('Obama', 1234, None) Called by the constructor def __init__(self, n, s, b): ""”Initializer: creates a Worker id8 Worker Has last name n, SSN s, and boss b lname 'Obama' Precondition: n a string, s an int in ssn 1234 range 0..999999999, and b either a Worker or None. boss None self.lname = n self.ssn = s self.boss = b 10/27/15 Methods and Operations 7

  8. Recall: The __init__ Method two underscores w = Worker('Obama', 1234, None) def __init__(self, n, s, b): ""”Initializer: creates a Worker Has last name n, SSN s, and boss b Are there other special methods Precondition: n a string, s an int in range 0..999999999, and b either that we can use? a Worker or None. self.lname = n self.ssn = s self.boss = b 10/27/15 Methods and Operations 8

  9. Example: Converting Values to Strings str() Function Backquotes • Usage : str( <expression> ) • Usage : ` <expression> ` § Evaluates the expression § Evaluates the expression § Converts it into a string § Converts it into a string • How does it convert? • How does it convert? § str(2) → '2' § `2` → '2' § str(True) → 'True' § `True` → 'True' § str('True') → 'True' § `'True'` → "'True'" § str(Point3()) → '(0.0,0.0,0.0)' § `Point3()` → "<class 'Point3'> (0.0,0.0,0.0)" 10/27/15 Methods and Operations 9

  10. Example: Converting Values to Strings str() Function Backquotes • Usage : str( <expression> ) • Usage : ` <expression> ` Backquotes are § Evaluates the expression § Evaluates the expression for unambigious § Converts it into a string § Converts it into a string representation • How does it convert? • How does it convert? What type is The value’s § str(2) → '2' § `2` → '2' this value? type is clear § str(True) → 'True' § `True` → 'True' § str('True') → 'True' § `'True'` → "'True'" § str(Point3()) → '(0.0,0.0,0.0)' § `Point3()` → "<class 'Point3'> (0.0,0.0,0.0)" 10/27/15 Methods and Operations 10

  11. What Does str() Do On Objects? class Point3(object): • Does NOT display contents """Instances are points in 3d space""" >>> p = Point3(1,2,3) … >>> str(p) def __str__(self): '<Point3 object at 0x1007a90>' """Returns: string with contents""" • Must add a special method return '('+self.x + ',' + § __str__ for str() self.y + ',' + self.z + ')' § __repr__ for backquotes • Could get away with just one def __repr__(self): § Backquotes require __repr__ """Returns: unambiguous string""" § str() can use __repr__ return str(self.__class__)+ (if __str__ is not there) str(self) 10/27/15 Methods and Operations 11

  12. What Does str() Do On Objects? class Point3(object): • Does NOT display contents """Instances are points in 3d space""" >>> p = Point3(1,2,3) … >>> str(p) def __str__(self): '<Point3 object at 0x1007a90>' """Returns: string with contents""" • Must add a special method return '('+self.x + ',' + § __str__ for str() self.y + ',' + self.z + ')' § __repr__ for backquotes Gives the • Could get away with just one def __repr__(self): class name § Backquotes require __repr__ """Returns: unambiguous string""" § str() can use __repr__ return str(self.__class__)+ (if __str__ is not there) str(self) __repr__ using __str__ as helper 10/27/15 Methods and Operations 12

  13. Special Methods in Python class Point3(object): • Have seen three so far """Instances are points in 3D space""" § __init__ for initializer … § __str__ for str() def __init__(self,x=0,y=0,z=0): § __repr__ for backquotes """Initializer: makes new Point3""" • Start/end with 2 underscores … § This is standard in Python def __str__(self,q): § Used in all special methods """Returns: string with contents""” § Also for special attributes … • For a complete list, see def __repr__(self,q): http://docs.python.org/reference """Returns: unambiguous string""” /datamodel.html … 10/27/15 Methods and Operations 13

  14. Returning to Fractions What We Want Operator Overloading 1 2 + 1 3 + 1 4 ∗ 5 • Python has methods that correspond to built-in ops 4 § __ add__ corresponds to + § __mul__ corresponds to * § Not implemented by default Why not use the • Implementing one allows you standard Python to use that op on your objects math operations? § Called operator overloading § Changes operator meaning 10/27/15 Methods and Operations 14

  15. Operator Overloading: Multiplication class Fraction(object): >>> p = Fraction(1,2) """Instance attributes: >>> q = Fraction(3,4) numerator: top [int] >>> r = p*q denominator: bottom [int > 0]""” def __mul__(self,q): Python """Returns: Product of self, q converts to Makes a new Fraction; does not modify contents of self or q >>> r = p.__mul__(q) Precondition: q a Fraction""" assert type(q) == Fraction top = self.numerator*q.numerator Operator overloading uses bot = self.denominator*q.denominator method in object on left. return Fraction(top,bot) 10/27/15 Methods and Operations 15

  16. Operator Overloading: Addition class Fraction(object): >>> p = Fraction(1,2) """Instance attributes: >>> q = Fraction(3,4) numerator: top [int] >>> r = p+q denominator: bottom [int > 0]""” def __add__(self,q): Python """Returns: Sum of self, q converts to Makes a new Fraction Precondition: q a Fraction""" >>> r = p.__add__(q) assert type(q) == Fraction bot = self.denominator*q.denominator top = (self.numerator*q.denominator+ Operator overloading uses self.denominator*q.numerator) method in object on left. return Fraction(top,bot) 10/27/15 Methods and Operations 16

  17. Comparing Objects for Equality class Fraction(object): • Earlier in course, we saw == """Instance attributes: compare object contents numerator: top [int] § This is not the default denominator: bottom [int > 0]""" § Default : folder names • Must implement __eq__ def __eq__(self,q): """Returns: True if self, q equal, § Operator overloading! False if not, or q not a Fraction""" § Not limited to simple if type(q) != Fraction: attribute comparison return False § Ex : cross multiplying left = self.numerator*q.denominator rght = self.denominator*q.numerator 4 1 2 4 return left == rght 2 4 10/27/15 Methods and Operations 17

Recommend


More recommend