-2

I know that static variables apply to an object and an instance variable (usually under the __init__() function) applies to an instance but a question came to mind:

When and where should static variables and instance variables be used in a game? Also, if you change the value of an object's static variable, does it apply to all instances of that object?

GhostCat
  • 137,827
  • 25
  • 176
  • 248

1 Answers1

0

Instance attributes should be used if the attributes are to be unique to the instances (which is the case most of the time). Class attributes can be used if the attributes should be shared among all instances, for example if you want to store constants that are related to this class. An example that comes to mind are the states of an entity (finite state machine):

from enum import Enum


class Entity:
    # The instances don't need their own `states` enumeration,
    # so I create one which will be shared among all instances.
    STATES = Enum('State', 'IDLING WALKING JUMPING')

    def __init__(self):
        self.state = self.STATES.JUMPING

    def update(self):
        if self.state is self.STATES.JUMPING:
            print('jumping')

entity = Entity()
entity.update()

Take care of mutable class attributes, because when you modify them, you modify them for all instances.

skrx
  • 19,980
  • 5
  • 34
  • 48
  • 1. So by setting state to one of the listed states, every instance of that object changes as well? For example, if you have many enemies on screen and you trigger a change in their state, every single enemy will change their state? – Protolaser 28 Oct 24 '18 at 12:21
  • @Protolaser28 No. Note how there's an *instance* attribute `state` and a *class* attribute `STATES`. So changing `state` of one `Entity` instance does not change other `Entity` instances. – sloth Oct 24 '18 at 13:56
  • What is an enumeration? Does it return a list? – Protolaser 28 Oct 24 '18 at 21:14
  • It's a type that is used as a replacement for magic numbers/strings. For example you could say `1` means idling, `2` walking, etc., then your code would be really difficult to read: `state = 2` (what state was 2 again?). Check out the [docs](https://docs.python.org/3/library/enum.html) and these answers: https://stackoverflow.com/questions/22586895/python-enum-when-and-where-to-use https://stackoverflow.com/questions/37601644/python-whats-the-enum-type-good-for – skrx Oct 27 '18 at 09:28