代码之家  ›  专栏  ›  技术社区  ›  Eric Auld

使用同一字典作为各种函数的参数,有些函数的参数较少

  •  1
  • Eric Auld  · 技术社区  · 7 年前

    我有几个函数都有一大堆相同的参数。他们中的一些人在这上面还有额外的论据。我想把同一本字典传给他们所有人,但那些争论较少的人会抱怨字典里有多余的条目。

    什么是最好的解决方案?将无用的伪参数放入参数较少的函数中?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Andrej Kesely    7 年前

    制作将使用 inspect 获取函数参数列表的模块。这将为您提供示例:

    import inspect
    
    def take_many_arguments(fn):
        origf = fn
        def _f(*arg, **args):
            new_args = {}
    
            for a in inspect.getargspec(origf).args:
                if a not in args:
                    continue
                new_args[a] = args[a]
    
            return origf(*arg, **new_args)
        return _f
    
    
    class C:
        @take_many_arguments
        def fn1(self, a):
            print(a)
    
        @take_many_arguments
        def fn2(self, a, b):
            print(a, b)
    
        @take_many_arguments
        def fn3(self, a, b, c):
            print(a, b, c)
    
    
    @take_many_arguments
    def fn4(a, b):
        print(a, b)
    
    
    d = {'a': 1, 'b': 2, 'c': 3}
    
    # for classes:
    c = C()
    c.fn1('Normal call')
    c.fn1(**d)
    c.fn2(**d)
    c.fn3(**d)
    
    # for functions:
    fn4(9, 8)
    fn4(**d)
    

    输出:

    Normal call
    1
    1 2
    1 2 3
    9 8
    1 2