AI summary by TwinMind

Lecture 20: Fitness Tracker Object-Oriented Programming Example

MIT OpenCourseWare

1h 19m 4s

Lecture Overview

  • Final lecture on object-oriented programming and creating custom data types with Python classes
  • Focus on creating comprehensive Fitness tracker object with workout class implementation
  • Reinforces concepts from previous lecture: getters/setters, class variables, inheritance
  • More involved example building incrementally

Two Perspectives of Object-Oriented Programming

  • Implementation perspective (left side): Making design decisions for new object/data type
    • Decide object name, attributes (data/procedures)
    • Create blueprint/abstract notion
  • Usage perspective (right side): Creating and manipulating instances
    • Create actual objects of the type
    • Manipulate objects in useful ways

Workout Class Design - Common Properties

  • Core attributes for all workout types:
    • Icon (emoji representation)
    • Kind of workout (biking, swimming, running)
    • Date (start/end dates and times)
    • Heart rate (average throughout activity)
    • Distance
    • Calories burned
  • Specific workout extensions:
    • Swimming: pace, stroke type, 100-yard splits
    • Running: cadence, running pace, mile splits, elevation
  • Implementation focus: Icon, kind, start time, end time, calories burned (italicized subset)

Simple Workout Class Implementation

  • Class definition: class Workout(object)
  • Constructor parameters: self, start_time, end_time, calories_burnt
  • Data attributes:
    • self.start (start time)
    • self.end (end time)
    • self.calories (calories burned)
    • self.icon (sweating person emoji by default)
    • self.kind ("workout" string by default)
  • Methods: Basic getter/setter methods for calories, start_time, end_time

Class and Instance State Dictionaries

  • Class state dictionary: Workout.__dict__.keys()
    • Contains all method definitions (init, getters, setters)
    • Values are memory locations of method definitions
    • Includes docstring via __doc__
  • Instance state dictionary: my_workout.__dict__
    • Contains actual data attribute values for specific instance
    • Keys: icon, kind, start, end, calories
    • Values: specific to that instance

Improved Workout Class with Class Variables

  • Class variable: cal_per_hour = 200 (calories burned per hour)
  • Enhanced init method:
    • Default calories parameter (calories=None)
    • DateTime object conversion using dateutil.parser.parse()
    • Stores start/end as datetime objects instead of strings
  • Improved get_calories method:
    • If calories provided: return provided value
    • If calories=None: estimate based on duration
    • Calculation: (end_time - start_time).total_seconds() / 3600 * cal_per_hour

DateTime Library Usage

  • Import: from dateutil import parser
  • Parsing: parser.parse(date_string) converts string to datetime object
  • Operations: Can subtract datetime objects to get TimeDelta
  • Methods: total_seconds() on TimeDelta objects
  • Flexibility: Accepts multiple date/time formats (Sept 30 2021, September 30, 2021, etc.)

Class Variables Access Patterns

  • Proper access: Within class definition methods
  • External access options (discouraged):
    • Workout.cal_per_hour (via class name)
    • instance.cal_per_hour (via instance)
    • Can modify: Workout.cal_per_hour = 250
  • Best practice: Create methods for accessing/modifying class variables

Inheritance Hierarchy Design

  • Parent class: Workout (base/super class)
  • Child classes: OutdoorWorkout, IndoorWorkout (subclasses)
  • Further specialization: Running, Swimming under OutdoorWorkout
  • Inheritance principle: Child class is-a parent class
  • Benefits: Inherit all parent attributes and methods, can add/override

RunWorkout Class Implementation

  • Parent: class RunWorkout(Workout)
  • Additional data attribute: elevation
  • Constructor: start, end, elevation=0, calories=None
  • Super() usage: super().__init__(start, end, calories)
    • Calls parent's init method
    • Alternative: Workout.__init__(self, start, end, calories)
  • Attribute overrides:
    • self.icon = running person emoji
    • self.kind = "running"
  • New methods: get_elevation(), set_elevation()

Method Inheritance and Reuse

  • Str method inheritance: Defined once in Workout class
  • Complex string building: Concatenates multiple components
    • Horizontal line border
    • Icon with vertical bars
    • Workout kind label
    • Duration (using get_duration method)
    • Calories (using get_calories method)
    • Bottom border
  • Automatic inheritance: All subclasses use same str method
  • Customization: Different icons/kinds per subclass type

Method Overriding - Enhanced get_calories

  • RunWorkout class variable: cal_per_kilometer = 100
  • GPS-based calculation: Optional GPS route points (latitude/longitude tuples)
  • Logic:
    • If GPS points provided: calculate distance between consecutive points
    • Multiply total distance by cal_per_kilometer
    • If no GPS points: call parent's get_calories method (super().get_calories())
  • GPS distance calculation: Uses helper function for lat/long distance calculation

Method Resolution Order

  • Search pattern:
    1. Check object's immediate class for method
    2. If not found, check parent class
    3. Continue up hierarchy to generic Python object
    4. Error if method not found anywhere
  • Override behavior: Child class method takes precedence over parent

Equality Comparison Implementation

  • Dunder method: __eq__(self, other)
  • Workout equality criteria:
    • Same type (type(self) == type(other))
    • Same start/end times
    • Same kind
    • Same calories
  • RunWorkout override:
    • Call parent equality: super().__eq__(other)
    • Additional check: same elevation
    • Modular approach shows clear differences

Key Programming Principles

  • Abstraction: Hide implementation details
  • Modularity: Build complex functionality incrementally
  • Information hiding: Use methods instead of direct attribute access
  • Code reusability: Inherit and extend existing functionality
  • Incremental development: Start simple, add features gradually

Best Practices and Warnings

  • Avoid over-engineering: Don't create complex class hierarchies unnecessarily
  • Balance complexity: Use simple functions/single classes when sufficient
  • Maintainability: Complex inheritance can make code hard to navigate
  • Future applications: Useful for building complex systems in advanced courses

TwinMind

Get summaries like this for your own meetings

TwinMind takes notes in the background during meetings, lectures, and calls, then writes the summary for you.

Free plan to get started

No bot joins your calls

Phone, desktop & Chrome apps

Your next meeting, summarized like this

TwinMind listens in the background and turns meetings, lectures, and calls into searchable notes you can chat with. Start free.

Available on phone, desktop & Chrome

Your next meeting, summarized like this

TwinMind listens in the background and turns meetings, lectures, and calls into searchable notes you can chat with. Start free.

Available on phone, desktop & Chrome

Your next meeting, summarized like this

TwinMind listens in the background and turns meetings, lectures, and calls into searchable notes you can chat with. Start free.

Available on phone, desktop & Chrome