Is there a better way to initialize this class? Python

Viewed 78

I'm passing in a row from a database which is being read in as a tuple. I like the idea of having these attributes readily available for all child classes, but this feels like it could be done without being so many lines. Is there a better method?

class Player():
    def __init__(self, player_attributes):
        self.player_id = player_attributes[0]
        self.player_first_name = player_attributes[1]
        self.player_last_name = player_attributes[2]
        self.player_date_of_birth = player_attributes[3]
        self.player_city_of_birth = player_attributes[4]
        self.player_state_of_birth = player_attributes[5]
        self.player_height = player_attributes[6]
        self.player_weight = player_attributes[7]
        self.player_age = player_attributes[8]
        self.player_hair_color = player_attributes[9]
        self.player_favorite_food = player_attributes[10]
        self.player_favorite_sport = player_attributes[11]
        ...(20 more attributes)
4 Answers

You can use dataclass

from dataclasses import dataclass


@dataclass
class Player:
    player_id: str
    player_first_name: str


player_attributes = ('713', 'Jack')

player: Player = Player(*player_attributes)
print(player)

output

Player(player_id='713', player_first_name='Jack')

You could use a for loop and the __dict__ attribute maybe.

Use a dictionary instead of a list and this template:

class Test:
     def __init__(self, dictio):
         for k, v in dictio.items():
             self.__dict__[k] = v

can you store player_attributes like dictionary?if so, you can use such tricky thing:

class A:

    def __init__(self, d):
        self.__dict__.update(d)

if __name__ == '__main__':
    a = A({'k': 123, 'd': 34})
    print(a.k)

You can use the locals() method to do dynamic assignment.

class Player:
  def __init__(self, db_record):
    for i,k in enumerate(('player_id', 'first_name', 'last_name', 'age')):
        locals()[k] = db_record[i]
    # Clean up local variables
    del db_record
    del i
    del k
    # Assign the local variables to __dict__
    self.__dict__.update(locals())


  def dump(self):
    print(repr(self.__dict__))
Related