The problem isn't with your understanding of decorators, it's with
your understanding of how Python interprets class definitions.

When Python steps through your code, it first creates a new class
called Engine. It then proceeds through the block of code under this
class definition, populating the class with methods and variables.
First off, it hits __init__, which is a simple function definition.
Note that at this point it doesn't execute the code under __init__, as
the class hasn't been instantiated, just defined. Next it hits the
definition of on_draw, with your decorator. This is where things go
wrong.

The name 'self' is not special in Python in any way. It's simply used
by convention for the first argument of instance methods. As the
interpreter isn't in an instance method at the moment, it has no idea
what 'self' means, which is the error message you're being given.

The fundamental problem here is that you're trying to give self.window
an event handler before self exists, let alone self.window. One way of
fixing this would be something like:

class Engine(object):
   def __init__(self):
       # Open a window.
       self.window = pyglet.window.Window()
       self.window.clear()
       self.window.on_draw = self.on_draw

       # Game loop.
       pyglet.app.run()

   def on_draw():
       print "MONKEY!"
       window.clear()

e = Engine()

Here you're defining a handler function when the class is defined, but
not associating it with the window until instantiation, when the
window exists. However, it's a little annoying to have to do this for
every handler function individually, so Pyglet provides a nicer way of
doing this:

class Engine(object):
   def __init__(self):
       # Open a window.
       self.window = pyglet.window.Window()
       self.window.clear()
       self.window.push_handlers(self)

       # Game loop.
       pyglet.app.run()

   def on_draw():
       print "MONKEY!"
       window.clear()

e = Engine()

Now when any event is dispatched by the window (including, but not
limited to on_draw), the engine will call its appropriate method, if
any.

Hope this helps,
Martin

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"pyglet-users" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/pyglet-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to