Lesson 28 Classes and Methods

  • View
    36

  • Download
    0

Embed Size (px)

DESCRIPTION

Lesson 28 Classes and Methods. Python Mini-Course University of Oklahoma Department of Psychology. Lesson objectives. Create methods inside class definitions Call methods using function syntax and method syntax Create custom __init__ and __str__ methods Use operator overloading. - PowerPoint PPT Presentation

Text of Lesson 28 Classes and Methods

  • Python Mini-CourseUniversity of OklahomaDepartment of Psychology Lesson 28Classes and Methods6/17/09Python Mini-Course: Lesson 28*

    Python Mini-Course: Lesson 28

  • Lesson objectivesCreate methods inside class definitionsCall methods using function syntax and method syntaxCreate custom __init__ and __str__ methodsUse operator overloading

    6/17/09Python Mini-Course: Lesson 28*

    Python Mini-Course: Lesson 28

  • EncapsulationData and behaviors are packaged togetherThe object only reveals the interfaces needed to interact with itInternal data and behaviors can remain hidden

    6/17/09Python Mini-Course: Lesson 28*

    Python Mini-Course: Lesson 28

  • Encapsulating the Time classInstead of using functions, we want to use methodsMove the functions inside the class definition6/17/09Python Mini-Course: Lesson 28*

    Python Mini-Course: Lesson 28

  • The print_time() methodclass Time(object): def print_time(self): """ Print the time in hour:minute:second format. """ print '%02d:%02d:%02d' % \ (self.hour, self.minute, self.second)

    6/17/09Python Mini-Course: Lesson 28*

    Python Mini-Course: Lesson 28

  • Calling a methodUsing function syntaxt1 = Time(2,35)Time.print_time(t1)Using method syntaxt1.print_time()6/17/09Python Mini-Course: Lesson 28*

    Python Mini-Course: Lesson 28

  • Converting the other functions to methodsThe valid_time methodThe increment methodThe add_time method

    6/17/09Python Mini-Course: Lesson 28*

    Python Mini-Course: Lesson 28

  • The valid_time methodclass Time(object): ... def valid_time(self): validity = True # All values must be at least zero if self.hour < 0 or self.minute < 0 \ or self.second < 0: validity = False # Minute and second must be base 60 if self.minute >= 60 or self.second >= 60: validity = False return validity

    6/17/09Python Mini-Course: Lesson 28*

    Python Mini-Course: Lesson 28

  • The increment methodclass Time(object): ... def increment(self, t2): # Check the input arguments if type(t2) != Time: raise AttributeError, \ 'invalid argument passed to Time.increment()' if not t2.valid_time(): raise ValueError, \ 'invalid Time object passed to Time.increment()' # Add the times self.hour += t2.hour self.minute += t2.minute self.second += t2.second

    6/17/09Python Mini-Course: Lesson 28*

    Python Mini-Course: Lesson 28

  • The add_time methodclass Time(object): ... def add_time(self, t2): # Add the times new_time = Time() new_time.hour = self.hour + t2.hour new_time.minute = self.minute + t2.minute new_time.second = self.second + t2.second # Return the sum return new_time

    6/17/09Python Mini-Course: Lesson 28*

    Python Mini-Course: Lesson 28

  • Using the Time classt1 = Time(0,0,30)t2 = Time(1,0,45)t1.increment(t2)t1.print_time()t3 = t1.add_time(t2)t3.print_time()t4 = Time.add_time(t1, t2)t4.print_time()6/17/09Python Mini-Course: Lesson 28*

    Python Mini-Course: Lesson 28

  • Improving the Time classProblems:FormattingMinutes and seconds should always be less than 60Printing is awkwardAdding times is awkwardSolutions: see time_oop1.py6/17/09Python Mini-Course: Lesson 28*

    Python Mini-Course: Lesson 28

  • Keeping the right formatclass Time(object): ... def adjust_base_60(self): # Increment minutes as necessary and adjust seconds self.minute += self.second // 60 self.second = self.second % 60 # Increment hours as necessary and adjust minutes self.hour += self.minute // 60 self.minute = self.minute % 606/17/09Python Mini-Course: Lesson 28*

    Python Mini-Course: Lesson 28

  • Controlling access to attributesclass Time(object): ... def set_time(self, hour=0, minute=0, second=0): self.hour = hour self.minute = minute self.second = second self.adjust_base_60()6/17/09Python Mini-Course: Lesson 28*

    Python Mini-Course: Lesson 28

  • The __str__ methodclass Time(object): def __str__(self): """ Return the time in hour:minute:second format. """ return '%02d:%02d:%02d' % \ (self.hour, self.minute, self.second)

    6/17/09Python Mini-Course: Lesson 28*

    Python Mini-Course: Lesson 28

  • The __str__ methodThe __str__ method is a special method that is called by the str() and print commandst1 = Time(2,45)str(t1)print t1

    6/17/09Python Mini-Course: Lesson 28*

    Python Mini-Course: Lesson 28

  • Why does this work?In Python, the most basic class, the object class, defines the __str__ methodTime is a sub-class of the object class, and it inherits this behaviorBy defining our own __str__ method we override the base class methodThis is polymorphism6/17/09Python Mini-Course: Lesson 28*

    Python Mini-Course: Lesson 28

  • Operator overloadingWe can also define how a class responds to standard operators such as +, -, etc.This is called operator overloading6/17/09Python Mini-Course: Lesson 28*

    Python Mini-Course: Lesson 28

  • The __add__ methodclass Time(object): ... def __add__(self, other): return self.add_time(other)

    def add_time(self, t2): new_time = Time() new_time.hour = self.hour + t2.hour new_time.minute = self.minute + t2.minute new_time.second = self.second + t2.second new_time.adjust_base_60() return new_time

    6/17/09Python Mini-Course: Lesson 28*

    Python Mini-Course: Lesson 28

  • Using the __add__ methodt1 = Time(0,0,30)t2 = Time(1,0,45)t3 = t1 + t2print t3print t1 + t26/17/09Python Mini-Course: Lesson 28*

    Python Mini-Course: Lesson 28

  • Type-based dispatchAllow us to use different types of arguments for the same method (or function)

    6/17/09Python Mini-Course: Lesson 28*

    Python Mini-Course: Lesson 28

  • class Time(object): ... def increment(self, t2): # Check the input arguments if type(t2) == Time: # Add the times self.hour += t2.hour self.minute += t2.minute self.second += t2.second elif type(t2) == int: # Increment the seconds self.second += t2 else: raise AttributeError, \ 'invalid argument passed to Time.increment()' self.adjust_base_60()6/17/09Python Mini-Course: Lesson 28*

    Python Mini-Course: Lesson 28

  • For more practice, tryThink Python. Chap 17Exercise 17.3, page 165Exercise 17.4, page 166Exercise 17.5, page 167Exercise 17.6, page 169 (debugging exercise)

    6/17/09Python Mini-Course: Lesson 28*

    Python Mini-Course: Lesson 28

  • AssignmentThink Python. Chap 18Read textType in and run code as you go (save as poker.py)Do Exercises 18.2 and 18.3 in text6/17/09Python Mini-Course: Lesson 28*

    Python Mini-Course: Lesson 28

    **