首页 > 解决方案 > 避免 if else 实例化一个类 - python

问题描述

我想根据字段的值创建一个类的对象。

例如:

if r_type == 'abc':
                return Abc()
            elif r_type == 'def':
                return Def()
            elif r_type == 'ghi':
                return Ghi()
            elif r_type == 'jkl':
                return Jkl()

什么是避免 if else here 的 Pythonic 方式。我正在考虑创建一个以 r_type 为键,类名为值的字典,并获取值并实例化,这是一种正确的方式,还是在 python 中有更好的惯用方式?

标签: pythondesign-patternsswitch-statementconditional

解决方案


您可以利用类是python 中的第一类对象这一事实,并使用字典来访问您要创建的类:

classes = {'abc': Abc,    # note: you store the object here
           'def': Def,    #       do not add the calling parenthesis
           'ghi': Ghi,
           'jkl': Jkl}

然后像这样创建类:

new_class = classes[r_type]()  # note: add parenthesis to call the object retreived

如果您的类需要参数,您可以像在普通类创建中一样放置它们:

new_class = classes[r_type](*args, *kwargs)

推荐阅读