Python 3 Object-Oriented Programming by Dusty Phillips

Python 3 Object-Oriented Programming by Dusty Phillips

Author:Dusty Phillips [Dusty Phillips]
Language: eng
Format: epub
Tags: COM051000 - COMPUTERS / Programming / General, COM051360 - COMPUTERS / Programming Languages / Python, COM051210 - COMPUTERS / Programming / Object Oriented
Publisher: Packt Publishing
Published: 2018-11-14T07:33:16+00:00


def one(timer):

format_time("Called One")

def two(timer):

format_time("Called Two")

def three(timer):

format_time("Called Three")

class Repeater:

def __init__(self):

self.count = 0

def repeater(self, timer):

format_time(f"repeat {self.count}")

self.count += 1

timer.call_after(5, self.repeater)

timer = Timer()

timer.call_after(1, one)

timer.call_after(2, one)

timer.call_after(2, two)

timer.call_after(4, two)

timer.call_after(3, three)

timer.call_after(6, three)

repeater = Repeater()

timer.call_after(5, repeater.repeater)

format_time("Starting")

timer.run()

This example allows us to see how multiple callbacks interact with the timer. The first function is the format_time function. It uses the format string syntax to add the current time to the message; we'll read about them in the next chapter. Next, we create three simple callback methods that simply output the current time and a short message telling us which callback has been fired.

The Repeater class demonstrates that methods can be used as callbacks too, since they are really just functions that happen to be bound to an object. It also shows why the timer argument to the callback functions is useful: we can add a new timed event to the timer from inside a presently running callback. We then create a timer and add several events to it that are called after different amounts of time. Finally, we start the timer running; the output shows that events are run in the expected order:

02:53:35: Starting 02:53:36: Called One 02:53:37: Called One 02:53:37: Called Two 02:53:38: Called Three 02:53:39: Called Two 02:53:40: repeat 0 02:53:41: Called Three 02:53:45: repeat 1 02:53:50: repeat 2 02:53:55: repeat 3 02:54:00: repeat 4

Python 3.4 introduced a generic event loop architecture similar to this. We'll be discussing it later, in Chapter 13, Concurrency.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.