Changing from_dict to classmethod.
This commit is contained in:
+19
-20
@@ -1,6 +1,5 @@
|
||||
"""File for Category class."""
|
||||
|
||||
from typing import Optional
|
||||
import json
|
||||
|
||||
from data.score import Score, ScoreTime # pylint: disable=import-error
|
||||
@@ -9,21 +8,30 @@ from data.score import Score, ScoreTime # pylint: disable=import-error
|
||||
class Category:
|
||||
"""Stores a category's information and relative scores."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
name: str,
|
||||
ascending: Optional[bool] = False,
|
||||
time_record: Optional[bool] = False,
|
||||
) -> None:
|
||||
def __init__(self, name: str, ascending: bool, time_record: bool, score_map: dict) -> None:
|
||||
self._name: str = name
|
||||
self._ascending: bool = ascending
|
||||
self._time_record: bool = time_record
|
||||
self._scores_map: dict(Score) = {}
|
||||
self._scores_map: dict = score_map
|
||||
|
||||
def __str__(self) -> str:
|
||||
"""Creates a string from the class."""
|
||||
return json.dumps(self.to_dict(), indent=4)
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, name: str, data: dict):
|
||||
"""Fills out category from passed dictionary"""
|
||||
ascending = data["ascending"]
|
||||
time_record = data["time_record"]
|
||||
score_map = {}
|
||||
for user, score in data["scores"].items():
|
||||
if time_record:
|
||||
score_map[user] = ScoreTime(user, score)
|
||||
else:
|
||||
score_map[user] = Score(user, score)
|
||||
|
||||
return cls(name, ascending, time_record, score_map)
|
||||
|
||||
@property
|
||||
def ascending(self) -> bool:
|
||||
"""Getter for ascending bool."""
|
||||
@@ -47,23 +55,14 @@ class Category:
|
||||
def add_score(self, score: Score) -> None:
|
||||
"""Adds a score to dictionary storage. Then sorts dictionary by score value."""
|
||||
if score.user in self._scores_map:
|
||||
del self._scores_map[score.user]
|
||||
self._scores_map[score.user] = score
|
||||
self._scores_map[score.user].value = score.value
|
||||
else:
|
||||
self._scores_map[score.user] = score
|
||||
|
||||
self._scores_map = dict(
|
||||
sorted(self._scores_map.items(), key=lambda x: x[1].score, reverse=not self.ascending)
|
||||
)
|
||||
|
||||
def from_dict(self, data: dict) -> None:
|
||||
"""Fills out category from passed dictionary"""
|
||||
self._ascending = data["ascending"]
|
||||
self._time_record = data["time_record"]
|
||||
for user, score in data["scores"].items():
|
||||
if self.time_record:
|
||||
self.add_score(ScoreTime(user, score))
|
||||
else:
|
||||
self.add_score(Score(user, score))
|
||||
|
||||
def get_user_score(self, user: str) -> Score:
|
||||
"""Gets a user's score. None if doesn't exist."""
|
||||
if user in self.scores:
|
||||
|
||||
Reference in New Issue
Block a user