Classes vs. Multiple Lists

First off, I’m new to Python and just trying to teach myself as I play around creating games. So I’m creating a game in pygame, where there are lots of circles being drawn and moved around. I’m storing all the data regarding the circles in several lists (Xposition, Yposition, Size, dx, dy, etc.). I recently started reading about classes and am wondering if there is any benefit to having the circles be a class with all this data stored in it? I can’t seem to understand if a class would be any better than just having several individual lists. Would classes speed up performance any? Or is there any better way to store/use that data? Thanks in advance.

In this case, use classes would be a development tool, making coding and future reading/updating easier. You would have to benchmark to find out for sure, but I suspect using a class would be slightly slower (due to instantiation and allocating MRO and the instance dict).

The best solution, with fantastic performance, would be a slotted dataclass (followed by a named tuple collections.nametuple, which doesn’t allow typing):

import dataclasses

@dataclasses.dataclass
class Circle:
    __slots__ = ("x_position", "y_position", "size", "dx", "dy")

    x_position: int
    y_position: int
    size: int
    dx: float
    dy: float

PS: “size” is ambiguous; I suggest “radius”

Edit: with Python 3.10 and later, you could instead specify dataclass(slots=True), and skip writing the __slots__ line

1 Like