python-3.x 如何排除或隐藏嵌套数据类中一个dict字段的部分值?

w46czmvw  于 2023-03-20  发布在  Python
关注(0)|答案(1)|浏览(118)

我有两个python数据类

@dataclass
class Grade:
    school: str = "school_default"
    classroom: str = "classroom_default"
    score: dict = field(default_factory= {'total':{'Math':100, 'English': 90, 'Chemistry':95, 'Password':11111}}, repr=True)

第二数据类的字段使用第一数据类作为:

@dataclass
class Student:
    name: str = "Alice"
    age:  int = field(default=10, repr=False)
    sex:  str = 'female'
    grade: Grade = None

如果我初始化Student数据类如下:

s1 = Student('Jimmy', 20, 'Male', Grade('school2', 'classroom2', {'total':{'Math':99, 'English':88, 
'Chemistry':77, 'Password':33333}}))

它将输出s1示例为

Student(name='Jimmy', sex='Male', grade=Grade(school='school2', classroom='classroom2', score={'total': {'Math': 99, 
'English': 88, 'Chemistry': 77, 'Password': 33333}}))

当我打印出学生数据类时,我如何排除或隐藏敏感数据,例如密码和化学字段?
我希望它将被打印出来:

Student(name='Jimmy', sex='Male', grade=Grade(school='school2', classroom='classroom2', score={'total': {'Math': 99, 
'English': 88, 'Chemistry': '******', 'Password': '******'}}))

我试过用

field(repr=False)

或将str方法重写为

def __str__(self):
        str_info = {
            k: v if k not in ['grade'] and v else '******' for k, v in self.__dict__.items()
        }
        return str(str_info)

但它将隐藏整个成绩值,而不是密码和化学

{'name': 'Jimmy', 'age': 20, 'sex': 'Male', 'grade': '******'}
0yg35tkg

0yg35tkg1#

您可以创建一个函数来隐藏敏感信息,并使用它重写Grade__repr__方法:

from dataclasses import dataclass, field

def hide_sensitive(score: dict):
    res = {}
    for k,v in score.items():
        if isinstance(v, dict):
            res[k] = hide_sensitive(v)
        elif k in ['Chemistry', 'Password']:
            res[k] = '******'
        else:
             res[k] = v
    return res

@dataclass
class Grade:
    school: str = "school_default"
    classroom: str = "classroom_default"
    score: dict = field(default_factory={'total':{'Math':100, 'English': 90, 'Chemistry':95, 'Password':11111}})

    def __repr__(self):
        return f'Grade(school={self.school}, classroom={self.classroom}, score={hide_sensitive(self.score)})'

@dataclass
class Student:
    name: str = "Alice"
    age:  int = field(default=10, repr=False)
    sex:  str = 'female'
    grade: Grade = None

s1 = Student('Jimmy', 20, 'Male', Grade('school2', 'classroom2', {'total':{'Math':99, 'English':88, 'Chemistry':77, 'Password':33333}}))

print(s1)

输出:

Student(name='Jimmy', sex='Male', grade=Grade(school=school2, classroom=classroom2, score={'total': {'Math': 99, 'English': 88, 'Chemistry': '******', 'Password': '******'}}))

请注意,打印s1.grade.score不会隐藏敏感信息,如果您希望实现这一点,可以定义一个Score类,该类具有自己的__repr__方法,该方法将直接打印hide_sensitive的输出。

相关问题