Skip to main content
Engineering LibreTexts

8.3: Another Example

  • Page ID
  • Here’s a version of increment (from Section 16.3) rewritten as a method:

    # inside class Time:
        def increment(self, seconds):
            seconds += self.time_to_int()
            return int_to_time(seconds)

    This version assumes that time_to_int is written as a method, as in Exercise 17.2.1. Also, note that it is a pure function, not a modifier.

    Here’s how you would invoke increment:

    >>> start.print_time()
    >>> end = start.increment(1337)
    >>> end.print_time()

    The subject, start, gets assigned to the first parameter, self. The argument, 1337, gets assigned to the second parameter, seconds.

    This mechanism can be confusing, especially if you make an error. For example, if you invoke increment with two arguments, you get:

    >>> end = start.increment(1337, 460)
    TypeError: increment() takes exactly 2 arguments (3 given)

    The error message is initially confusing, because there are only two arguments in parentheses. But the subject is also considered an argument, so all together that’s three.