我想创建一个类来存储在init中发生的关键错误的列表。
class Basic:
missing_view_data_columns = []
def __init__(self, some_dict):
self.some_dict = some_dict
try:
self.basic_1 = self.some_dict['basic_1']
self.basic_2 = self.some_dict['basic_2']
except KeyError as e:
self.add_missing_data_column(e)
@classmethod
def add_missing_data_column(cls, column_name):
cls.missing_view_data_columns.append(column_name)
class Specific(Basic):
def __init__(self, some_dict):
super().__init__(some_dict)
try:
self.specific_1 = self.some_dict['specific_1']
self.specific_2 = self.some_dict['specific_2']
except KeyError as e:
self.add_missing_data_column(e)
rem = Specific({})
print(f"missing_keys: {rem.missing_view_data_columns}")
这是我的方法,但是不起作用。以下代码将仅打印出现的第一个关键错误。我也可以说它看起来不太好,因为我需要两次编写相同的异常。
您能给我建议如何创建此功能吗?
您可以实现自己的字典:
from collections.abc import Mapping
class MissingDict(Mapping):
def __init__(self, d, cls):
self._d = d
self.cls = cls
def __getitem__(self, i):
if i in self._d:
return self._d[i]
self.cls.add_missing_data_column(i)
def __iter__(self): return iter(self._d)
def __len__(self): return len(self._d.keys())
这将存储字典实例并在您尝试访问新键时更新您班级的缺失列表。像这样使用:
class Basic:
missing_view_data_columns = []
def __init__(self, some_dict):
self.some_dict = MissingDict(some_dict, self)
self.basic_1 = self.some_dict['basic_1']
self.basic_2 = self.some_dict['basic_2']
@classmethod
def add_missing_data_column(cls, column_name):
cls.missing_view_data_columns.append(column_name)
class Specific(Basic):
def __init__(self, some_dict):
super().__init__(some_dict)
self.specific_1 = self.some_dict['specific_1']
self.specific_2 = self.some_dict['specific_2']
rem = Specific({})
print(f"missing_keys: {rem.missing_view_data_columns}")
显示:
missing_keys: ['basic_1', 'basic_2', 'specific_1', 'specific_2']
我已经修改了您的代码以遍历您要检查的每个键:
class Basic:
missing_view_data_columns = []
def __init__(self, some_dict):
self.some_dict = some_dict
keys = ['basic_1', 'basic_2']
for key in keys:
self.check_for_key_error(key)
def check_for_key_error(self, key):
try:
self.key = self.some_dict[key]
except KeyError as e:
self.add_missing_data_column(e)
@classmethod
def add_missing_data_column(cls, column_name):
cls.missing_view_data_columns.append(column_name)
class Specific(Basic):
def __init__(self, some_dict):
super().__init__(some_dict)
keys = ['basic_1', 'basic_2']
for key in keys:
self.check_for_key_error(key)
rem = Specific({})
print(f"missing_keys: {rem.missing_view_data_columns}")
输出:
missing_keys: [KeyError('basic_1'), KeyError('basic_2'), KeyError('basic_1'), KeyError('basic_2')]
您确定您确实要存储异常消息吗?因为看起来您只想知道字典中缺少哪些键。在这种情况下,您应该只使用dictionary.get()
方法,如果不存在密钥,则该方法将返回None
。如果失败,还可以设置默认返回值,例如dictionary.get(something, "return this if not found")
。找不到的密钥列表可以像这样完成:
keys_to_look_for = ["key_1", "key_2", "key_n"]
return [k for k in keys_to_look_for if not some_dict.get(k)]
您可以在不使用try/except
块的情况下解决问题:这是执行此操作的代码,
class Basic:
missing_view_data_columns = []
def __init__(self, some_dict):
self.some_dict = some_dict
self.basic_1 = self.some_dict.get('basic_1') or self.add_missing_data_column(KeyError('basic_1'))
self.basic_2 = self.some_dict.get('basic_1') or self.add_missing_data_column(KeyError('basic_2'))
@classmethod
def add_missing_data_column(cls, column_name):
cls.missing_view_data_columns.append(column_name)
class Specific(Basic):
def __init__(self, some_dict):
super().__init__(some_dict)
self.specific_1 = self.some_dict.get('specific_1') or self.add_missing_data_column(KeyError('specific_1'))
self.specific_2 = self.some_dict.get('specific_2') or self.add_missing_data_column(KeyError('specific_2'))
rem = Specific({ "specific_1": 1})
print(f"missing_keys: {rem.missing_view_data_columns}")
希望这会有所帮助!