具有dict的以下子类,我需要以可以返回ValuesView[tuple]
和ItemsView[str, tuple]
的方式重写items()和values()方法
这是我正在编码的课程:
from typing import ItemsView
VALUES = "VALUES"
OPERATORS = "OPERATORS"
class Query(dict):
def __init__(self, operators: dict = {}, values: dict = {}) -> None:
super().__init__()
if not operators.keys() == values.keys():
raise Exception("Keys of operators and values must be the same!!!")
self[OPERATORS]: dict[str, str] = operators
self[VALUES]: dict[str, int | float | str | list] = values
def get_fields(self) -> list:
return self[OPERATORS].keys()
def get_operators(self) -> dict:
return self[OPERATORS]
def get_values(self) -> dict:
return self[VALUES]
def __getitem__(self, k: str) -> dict or tuple:
try:
return super().__getitem__(k)
except KeyError:
operator = self.get_operators()[k]
value = self.get_operators()[k]
return operator, value
def keys(self) -> KeysView[str]:
return self[OPERATORS].keys()
def values(self) -> ValuesView[tuple]:
# Here I should return tuples (self[OPERATORS][key], self[VALUES][key]
# return super().values()
def items(self) -> ItemsView[str, tuple]:
# return super().items()
如何建立这样的视图?
更新
作为临时解决方案,我正在使用List comprehensions
,它可以完成工作,但不是100%。当然,我想知道构建这些视图的适当方法,因为它们与列表不同。
def values(self) -> ValuesView[tuple]:
return [(self[OPERATORS][key], self[VALUES][key]) for key in self.keys()]
def items(self) -> ItemsView[str, tuple]:
return [(key, (self[OPERATORS][key], self[VALUES][key])) for key in self.keys()]