10.4.2 Class Time Definition

Class Time: __init__ Method with Default Parameter Values

  • Specifies hour, minute and second parameters, each with a default argument of 0
  • The statements containing self.hour, self.minute and self.second appear to create hour, minute and second attributes for the new Time object (self)
  • These statements actually call methods that implement the class’s hour, minute and second properties
  • Those methods create attributes named _hour, _minute and _second
# timewithproperties.py
"""Class Time with read-write properties."""

class Time:
    """Class Time with read-write properties."""

    def __init__(self, hour=0, minute=0, second=0):
        """Initialize each attribute."""
        self.hour = hour  # 0-23
        self.minute = minute  # 0-59
        self.second = second  # 0-59

Class Time: hour Read-Write Property

  • Methods named hour define a publicly accessible read-write property named hour that manipulates a data attribute named _hour
  • The single-leading-underscore (_) naming convention indicates that client code should not access _hour directly
  • Properties look like data attributes to programmers working with Time objects, but are implemented as methods
  • Each property defines a getter method which gets (returns) a data attribute’s value
  • Each property can optionally define a setter method which sets a data attribute’s value
@property
    def hour(self):
        """Return the hour."""
        return self._hour

    @hour.setter
    def hour(self, hour):
        """Set the hour."""
        if not (0 <= hour < 24):
            raise ValueError(f'Hour ({hour}) must be 0-23')

        self._hour = hour

Class Time: hour Read-Write Property (cont.)

  • The @property decorator precedes the property’s getter method, which receives only a self parameter
  • A decorator adds code to the decorated function
    • Makes the hour function work with attribute syntax
  • getter method’s name is the property name

Class Time: hour Read-Write Property (cont.)

  • A decorator of the form @property_name.setter (@hour.setter) precedes the property’s setter method
  • Method receives two parameters—self and a parameter (hour) representing the value being assigned to the property
  • __init__ invoked this setter to validate __init__’s hour argument before creating and initializing the object’s _hour attribute
  • A read-write property has both a getter and a setter
  • A read-only property has only a getter

Class Time: minute and second Read-Write Properties

  • The following methods named minute and second define read-write minute and second properties
  • Each property’s setter ensures that its second argument is in the range 0–59 (the valid range of values for minutes and seconds)
@property
    def minute(self):
        """Return the minute."""
        return self._minute

    @minute.setter
    def minute(self, minute):
        """Set the minute."""
        if not (0 <= minute < 60):
            raise ValueError(f'Minute ({minute}) must be 0-59')

        self._minute = minute

    @property
    def second(self):
        """Return the second."""
        return self._second

    @second.setter
    def second(self, second):
        """Set the second."""
        if not (0 <= second < 60):
            raise ValueError(f'Second ({second}) must be 0-59')

        self._second = second

Class Time: Method set_time

  • Method set_time changes all three attributes with a single method call
  • The method uses the class's properties defined above
def set_time(self, hour=0, minute=0, second=0):
        """Set values of hour, minute, and second."""
        self.hour = hour
        self.minute = minute
        self.second = second

Class Time: Special Method __repr__

  • When you pass an object to built-in function repr—which happens implicitly when you evaluate a variable in an IPython session—the corresponding class’s __repr__ special method is called to get a string representation of the object
def __repr__(self):
        """Return Time string for repr()."""
        return (f'Time(hour={self.hour}, minute={self.minute}, ' + 
                f'second={self.second})')

Class Time: Special Method __repr__ (cont.)

  • The Python documentation indicates that __repr__ returns the “official” string representation of the object
  • Should look like a constructor expression that creates and initializes the object

Class Time: Special Method __str__

  • __str__ special method is called implicitly when you
    • convert an object to a string with the built-in function str
    • print an object
def __str__(self):
        """Print Time in 12-hour clock format."""
        return (('12' if self.hour in (0, 12) else str(self.hour % 12)) + 
                f':{self.minute:0>2}:{self.second:0>2}' + 
                (' AM' if self.hour < 12 else ' PM'))

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.