Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Classes with attributes but no methods

I am a beginner, but I am trying to implement a board game (Orleans) in python. I have created a class for the game state, and a class for each player. I had thought about creating a class for each type of action space, and creating an instance of the action space for each player since each player has a common set of action spaces. Each of these action space classes have some attributes, normally set in an __init__() method. However they have no other methods. Is this a good use of classes, or should I just change the code to work with lots of separate variables instead? The reason I made them classes was so that the naming of the variables would be more intuitive. The code below gives an example of the player class and two of the action space classes:

class Player:

    def __init__(self, start_characters, name):
        // other attributes
        self.farmhouse = Farmhouse()
        self.village = Village()

class Farmhouse:

    def __init__(self):
        self.boatman = False
        self.craftsman = False

class Village:

    def __init__(self):
        self.farmer = False
        self.boatman = False
        self.craftsman = False

The game state class will then have functions that will take a player instance as an argument, testing whether an action space has each of the appropriate requirements to trigger that action.

like image 251
TaxpayersMoney Avatar asked Oct 06 '18 13:10

TaxpayersMoney


2 Answers

Doing this is called an "Anemic object" or "Anemic domain" model.

Some consider this an anti-pattern and some not. I generally favor an anemic model as it proves to be a little more readable and scalable in my taste.

Instead of creating classes like that though, I highly suggest you to use dataclasses for this type of behavior.

Another option, for immutable types is to use namedtuples.

like image 122
Bharel Avatar answered Nov 11 '22 22:11

Bharel


That's good for readability, and there is no problem in defining classes that essentially group related data together. You may even want to do that to reduce the number of arguments you need to pass to a function, for example. As for having just a method, if this wasn't really about data, I would say define functions instead. Not the case here.

What alternatives do you have? Maybe setup dicts in __init__ with setting names in the keys. Not much different behind the scenes.

I prefer your option for the resulting access syntax.

like image 42
progmatico Avatar answered Nov 11 '22 21:11

progmatico