[Tutor] Why use decorators ?

Kent Johnson kent37 at tds.net
Sat May 2 13:11:04 CEST 2009


On Sat, May 2, 2009 at 1:41 AM, sudhanshu gautam
<sudhanshu9252 at gmail.com> wrote:
> Last night was using a pyglet for creating some good graphical applications
> ,it was my first introduction with the pyglet,so just went on pyglet.org and
> downloaded a pdf file .
>
> Now simply made two programs that is mentioned in the pdf of the pyglet
>
>
>
> program 1.It is simple program that prints 'HELLO WORLD'
>
>
> program2.It is simple takes the keyboard and mouse events
>
>
> Now I am going to write both the code then regarding queries also.
>
> 1.import pyglet
> window=pyglet.window.Window()
>
> lable=pyglet.text.Lable('Hello, world',
>  font_name='Times New Roman',
>  font_size=36,
>  x=window.width//2, y=window.height//2,
>  anchor_x='center', anchor_y='center')
> @window.event
> def on_draw():
>     window.clear()
>     label.draw()
> pyglet.app.run()
>
> okay I just drop second example just tell me why we are using that all the
> code that is showed in RED color .

That is the code that draws the window.

> 2What is Event Handlers as well as What is DECORATORS TELL ME ALSO

Most GUI frameworks are "event-driven". This means that the flow of
control is driven by things the user does, such as press a key or
click the mouse. User actions create events. Much of a GUI program is
written as event handlers - bits of code that respond to a particular
user action.

This is very different from, for example, a procedural style program
where the flow of control starts in a main function and proceeds
through a sequence of subroutine calls until it exits.

GUI frameworks differ in how the event handlers are defined and
connected to the framework. pyglet seems to use naming conventions to
define the event to be handled. on_draw() is handling a request to
draw the window.

Decorators are a syntactic shortcut. What you have written could also
be written as
def on_draw():
  ...
on_draw = window.event(on_draw)

I have a longer explanation here:
http://personalpages.tds.net/~kent37/kk/00001.html

Kent


More information about the Tutor mailing list