Python 有没有一种方法可以压缩此代码,而不是使用一个大的if-else块?

Python 有没有一种方法可以压缩此代码,而不是使用一个大的if-else块?,python,openpyxl,Python,Openpyxl,编写一个将样式应用于单元格区域的函数,想知道是否有某种元编程方法可以避免这里有一个大的if-else块。比如能够从映射自Type->attribute的字典中获取要设置的属性 def _apply_style_to_range(self, cell_range, style): for row in self.worksheet[cell_range]: for cell in row: if isinstance(style, openpyxl.

编写一个将样式应用于单元格区域的函数,想知道是否有某种元编程方法可以避免这里有一个大的if-else块。比如能够从映射自Type->attribute的字典中获取要设置的属性

def _apply_style_to_range(self, cell_range, style):
    for row in self.worksheet[cell_range]:
        for cell in row:
            if isinstance(style, openpyxl.styles.Alignment):
                self.worksheet[cell.coordinate].alignment = style
            elif isinstance(style, openpyxl.styles.Border):
                self.worksheet[cell.coordinate].border = style
            elif isinstance(style, openpyxl.styles.PatternFill):
                self.worksheet[cell.coordinate].fill = style
            elif isinstance(style, openpyxl.styles.Font):
                self.worksheet[cell.coordinate].font = style
            elif style in Numbers.all_number_formats: # these are custom strings I came up with so no defining type
                self.worksheet[cell.coordinate].number_format = style
            else:
                raise ValueError('unhandled style {} unable to be applied'.format(style))

这就是我能想到的

def _apply_style_to_range(self, cell_range, style):
    style_dict = {
        openpyxl.styles.Alignment: "alignment",
        openpyxl.styles.Border: "border",
        openpyxl.styles.PatternFill: "fill",
        openpyxl.styles.Font: "font",
    }

    attr_to_set = style_dict.get(type(style), None)
    if attr_to_set is None and style in Numbers.all_number_formats:
        attr_to_set = "number_format"

    if attr_to_set is None:
        raise ValueError('unhandled style {} unable to be applied'.format(style))

    for row in self.worksheet[cell_range]:
        for cell in row:
            self.worksheet[cell.coordinate].__setattr__(attr_to_set, style)

使用命名样式。使用
setattr(obj,key,value)
而不是直接访问
\uuu setattr\uuuu
。注意:1)使用
setattr
函数,不要直接调用
\uu setattr\uuuuu
,例如
setattr(self.worksheet[cell.coordination],attr\u to\u set,style)
。2) 如果涉及子类,这将不起作用;如果
style
可能是openpyxl.styles.Alignment的子类的实例,则无法识别它。3) 在函数外部定义
style\u dict
,否则每次调用时都会重新创建它(删除
dict
查找在顺序
if
检查中提供的任何节省)。