[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] Problem accessing pygame.Rect() members



Jake b wrote:
> (1) The documentation says that these aren't members( .top, .left,
> etc...), but are virtual attributes. What is a virtual attribute?

I would guess Python "intercepts" the request for the members .top,
.left, etc., and computes them on-the-fly. Sometimes these could be
called "computed attributes", and if you were writing them in Python
you'd use the "property" builtin to use them.

> (2) What's wrong with my code?

In Pygame, "rect" variables aren't always Rect objects. Tuples are
also valid as rects -- the tuple (x, y, w, h) is interpreted the same
as Rect(x, y, w, h). This error:

> AttributeError: 'tuple' object has no attribute 'left' on line:
> 	spr.rect.left = 40

indicates you believed your object was a rect when in fact it was
merely a tuple. Many pygame functions treat tuples as though they were
the corresponding Rect, but the objects are different and the tuple
object doesn't have the same attributes, methods, etc.

I haven't looked at your code more deeply than that, though, so I
can't say where you are getting a tuple from, when you expected a rect
object.

Here's a brief exploration of converting Rects to tuples:

$ python
Python 2.4.4 (#2, Aug 16 2007, 02:03:40)
[GCC 4.1.3 20070812 (prerelease) (Debian 4.1.2-15)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pygame
>>> tup = (10, 10, 20, 20)
>>> r = pygame.Rect(*tup)
>>> r
<rect(10, 10, 20, 20)>
>>> pygame.Rect(*r)
<rect(10, 10, 20, 20)>
>>> pygame.Rect(tup)
<rect(10, 10, 20, 20)>
>>> pygame.Rect(r)
<rect(10, 10, 20, 20)>
>>> tuple(r)
(10, 10, 20, 20)

As you can see, calling pygame.Rect(*obj) will give you a Rect object,
regardless of whether obj is a Rect or a tuple. pygame.Rect(obj) will
do the same thing.

Hope this helps!

Ethan

Attachment: signature.asc
Description: OpenPGP digital signature