您在這裡

Another example

8 九月, 2015 - 10:52

Here’s a version of increment (from Modifiers) 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.1 in Printing objects. Also, note that it is a pure function, not a modifier.

Here’s how you would invoke increment:

>>> start.print_time()09:45:00>>> end = start.increment(1337)>>> end.print_time()10:07:17

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.