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

Re: [pygame] Fwd: [Tutor] A more Pythonic way to do this



>
>                     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