Patternite Logo

Sharing common variables between all class instances in Python


By using class variables, we can share and update common variables between all instances of a class


In this example, we have a swarm of drones that we want to move together in a synchronized fashion (i.e. they should all move in the same direction). Changing the direction of the drones could be achieved by updating a direction instance variable in each Drone instance, however this would require looping through all drones and performing the update - an operation that could be slow, and prone to errors (especially with more sophisticated update logic).

Instead, we use a class variable called direction on line #7, which is shared between all instances of the Drone class. Then, whenever we call the class method change_direction on line #11, we update direction for all Drone instances at once. Calling the move method on line #17 for a given instance will update the current_position of that drone based on direction, as determined by whatever logic we've implemented in our handle_move function (not included here, as it goes beyond the scope of this pattern).

Using class variables in this way can be a simple-but-powerful approach to sharing state between, and "broadcasting" state updates to, class instances.

Profile picture for duncster

| edited

Patternite © 2022

Patternite Logo