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

Re: [pygame] How to manage image source Rect()'s for units



Jake b wrote:

How do I do a test in my .add() method to check if the sprite added
has a member named '.rect_source' ? ( Because if it does not, I'll
default it to its .image.get_rect() )


Just access the attribute and catch the exception if it is not present.

def add(self, sprite):
   try:
       rc = sprite.rect_source
   except AttributeError:
       rc = sprite.image.get_rect()

or something like that.

Python developers follow the philosophy that it is easier to ask for forgiveness than permission. That is, catching exceptions makes for cleaner code then using tests and conditional statements.

if hasattr(sprite, 'rect_source'):
   rc = sprite.rect_source
else:
   rc = sprite.image.get_rect()

In this case the attribute rect_source is named twice, in the test and the actual attribute access. That's one more time than necessary.

--
Lenard Lindstrom
<len-l@xxxxxxxxx>