首页 > 解决方案 > 在 __init__ 函数中处理多个参数的优雅方式

问题描述

我有跟随 init 函数,它接收很多 args 来运行类(如果用户不输入任何内容或者可以是用户输入的值,则 args 是默认值)。在不失去可读性的情况下减少变量数量(不在 init 中显示很多 args)的最优雅的方法是什么?使用 *args 函数(如def__init__(self, *args))?

    class World(object):

        def __init__(self, grid_size=(GRID_WIDTH, GRID_HEIGHT),
                     cell_size=(CELL_WIDTH, CELL_HEIGHT),
                     obstacles_position= OBSTACLES,
                     recharge_position= RECHARGE_ZONE,
                     treadmill_position= TREADMILL_ZONE,
                     workers_positions= WORKERS_POS,
                     delivery_positions= DELIVERY_ZONE):
         # some code bellow
    def main():
       # init some libraries
       world = worldGrid()
       # Do a while loop with the input variables from the world class

    if __name__ = '__main__':
       main()

Obs:我正在使用 Python 3+

标签: pythonpython-3.x

解决方案


在我看来,您可能应该坚持使用函数头中的所有函数参数(就像您目前拥有的那样)。这使您的代码更具可读性,允许 Python 告诉您可能省略了哪些参数,与 Python 的内置help()方法很好地配合,允许第三方 IDE 代码提示等,等等......


如果你真的想缩短函数头,你可以使用*argsand **kwargswhich 将接受任何可变参数,例如:

def func(self, *args, **kwargs):
    print("args:", args)
    print("kwargs:", kwargs)

用法如下所示:

>>> func(1, 2, 3, one="one", two="two")
args: (2, 3)
kwargs: {'one': 'one', 'two': 'two'}

因此,理论上您可以将您的类重构为如下所示。这段代码根本不处理默认值或任何错误检查——它只是将任何关键字参数设置为类本身的属性:

class World(object):
    def __init__(self, **kwargs):
        for key, value in kwargs.items():
            setattr(self, key, value)

和用法:

>>> w = World(one=1, two=2, three=3)
>>> w.one
1
>>> w.two
2
>>> w.three
3

推荐阅读