Search code examples
pythonstructpython-dataclassespython-class

Python data classes. Can't use arguments as elements in list


So I just stumbled upon python data classes after looking for something like a struct from the C-family. It's just that I don't understand why you can't do stuff like this:

@dataclass
class Player:
    gridx: float
    gridy: float
    rotation: float
    pos = [gridx, gridy]

player = Player(2.5, 5.5, PI)

It says that gridx is not defined. Maybe I've just understood structs wrong and you can't even do this in languages like C. I thought it would just be similar to the __init__ method in normal python classes where you could do pretty much whatever you want.


Solution

  • from dataclasses import dataclass
    from math import pi
    
    @dataclass
    class Player:
        gridx: float
        gridy: float
        rotation: float
    
        @property
        def pos(self):
            return [self.gridx, self.gridy]
    
    player = Player(2.5, 5.5, pi)
    print(player.pos)
    

    output

    [2.5, 5.5]
    

    It's up to you if you want to allow setting pos in order to change gridx and gridy (i.e. @pos.setter)