[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]
Re: [pygame] Fwd: [Tutor] A more Pythonic way to do this
- To: pygame-users@xxxxxxxx
- Subject: Re: [pygame] Fwd: [Tutor] A more Pythonic way to do this
- From: Shandy Brown <sjbrown@xxxxxxxxx>
- Date: Tue, 5 Jul 2005 21:29:22 -0400 (EDT)
- Delivered-to: archiver@seul.org
- Delivered-to: pygame-users-outgoing@seul.org
- Delivered-to: pygame-users@seul.org
- Delivery-date: Tue, 05 Jul 2005 21:29:37 -0400
- In-reply-to: <8daabe5605070516351857d85e@mail.gmail.com>
- References: <8daabe5605063015111d32477a@mail.gmail.com> <002b01c57e5e$609fd400$8f5328cf@JSLAPTOP> <8daabe560507011058b30809b@mail.gmail.com> <42C5B888.6000708@po-box.mcgill.ca> <8daabe5605070115567afb6c39@mail.gmail.com> <42C5CC7D.4070705@po-box.mcgill.ca> <8daabe5605070117216b20c08a@mail.gmail.com> <be4fbf9205070206397f35dfed@mail.gmail.com> <8daabe56050705115964075b58@mail.gmail.com> <be4fbf9205070515584d510fd9@mail.gmail.com> <8daabe5605070516351857d85e@mail.gmail.com>
- Reply-to: pygame-users@xxxxxxxx
- Sender: owner-pygame-users@xxxxxxxx
>
> for each in (enemyship_sprites.sprites()):
> each.rect.centerx = Enemy.initialx
> each.rect.centery = Enemy.initialy
>
The symptom is that they are all painting on top of each other in the same
position. Correct?
The confusion here is between *class* attributes and *object* attributes
(or more pythonically speaking, *instance* attributes).
In your program, there is only one thing called "Enemy" and that is a
class. You can make an instance of this Enemy class by doing something
like
enemy1 = Enemy()
Both "enemy1" and "Enemy" can have attributes.
class Enemy:
someVar = 90
def __init__(self):
self.pants = 44
We usually just call "pants" an attribute, but we usually give special
significance to "someVar" and call it a "class attribute" -- it is common
across all instances of that class
You can see how it's common by doing this:
enemy1 = Enemy()
enemy2 = Enemy()
print enemy1.someVar
print enemy2.someVar
Enemy.someVar = 314
print enemy1.someVar
print enemy2.someVar
They both changed when we changed the class attribute.
Anyway enough lecturing. The basic rule is stay away from class
attributes unless you need them. Just use instance attributes by defining
attributes in your __init__() function, like "pants" above.
-sjbrown