Create table class.
This commit is contained in:
@@ -0,0 +1,65 @@
|
|||||||
|
"""File for Table class."""
|
||||||
|
|
||||||
|
from typing import Optional
|
||||||
|
import json
|
||||||
|
|
||||||
|
from data.category import Category # pylint: disable=import-error
|
||||||
|
|
||||||
|
|
||||||
|
class Table:
|
||||||
|
"""Stores a table's information a list of categories."""
|
||||||
|
|
||||||
|
def __init__(self, name: str, message_id: Optional[int] = 0) -> None:
|
||||||
|
self._name: str = name
|
||||||
|
self._message_id: int = message_id
|
||||||
|
self._categories_map: "dict[Category]" = {}
|
||||||
|
|
||||||
|
def __str__(self) -> str:
|
||||||
|
return json.dumps(self.to_dict(), indent=4)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def categories(self) -> "list[Category]":
|
||||||
|
"""Returns list of categories."""
|
||||||
|
return self._categories_map.values()
|
||||||
|
|
||||||
|
@property
|
||||||
|
def message_id(self) -> int:
|
||||||
|
"""Getter for message id."""
|
||||||
|
return self._message_id
|
||||||
|
|
||||||
|
@message_id.setter
|
||||||
|
def message_id(self, m_id: int) -> None:
|
||||||
|
"""Setter for message id."""
|
||||||
|
self._message_id = m_id
|
||||||
|
|
||||||
|
@property
|
||||||
|
def name(self) -> str:
|
||||||
|
"""Getter for name."""
|
||||||
|
return self._name
|
||||||
|
|
||||||
|
def add_category(self, category: Category) -> None:
|
||||||
|
"""Adds a category to dictionary of categories. Shouldn't already exist."""
|
||||||
|
if category.name not in self._categories_map:
|
||||||
|
self._categories_map[category.name] = category
|
||||||
|
|
||||||
|
def from_dict(self, data: dict) -> None:
|
||||||
|
"""Fills out table from passed dictionary."""
|
||||||
|
self.message_id = data["message_id"]
|
||||||
|
for name, cat in data["categories"]:
|
||||||
|
category = Category(name)
|
||||||
|
category.from_dict(cat)
|
||||||
|
self.add_category(category)
|
||||||
|
|
||||||
|
def get_category(self, category_name: str) -> Category:
|
||||||
|
"""Retrieves category with the gven name."""
|
||||||
|
return self._categories_map[category_name]
|
||||||
|
|
||||||
|
def to_dict(self) -> dict:
|
||||||
|
"""Saves table as a python dictionary."""
|
||||||
|
data = {}
|
||||||
|
data["message_id"] = self.message_id
|
||||||
|
data["categories"] = {}
|
||||||
|
for category in self.categories:
|
||||||
|
data["categories"][category.name] = category.to_dict()
|
||||||
|
|
||||||
|
return data
|
||||||
Reference in New Issue
Block a user