代码之家  ›  专栏  ›  技术社区  ›  Htechno

用大量参数编写函数/方法的方法

  •  8
  • Htechno  · 技术社区  · 16 年前

    想象一下:

    def method(self, alpha, beta, gamma, delta, epsilon, zeta, eta, theta, iota, kappa):
        pass
    

    这条线跨越了79个字符,那么,多行的蟒蛇式方法是什么?

    6 回复  |  直到 7 年前
        1
  •  6
  •   Ignacio Vazquez-Abrams    16 年前

    我缩进后面的行2个级别:

    def method(self, alpha, beta, gamma, delta, epsilon, zeta, eta,
            theta, iota, kappa):
        pass
    
        2
  •  20
  •   David Z    16 年前

    您可以在括号(或括号)中包含换行符,例如

    def method(self, alpha, beta, gamma, delta, epsilon, zeta,
                     eta, theta, iota, kappa):
        pass
    

    (当然,要包含的空白数量由您决定)

    但在这种情况下,你也可以考虑

    def method(self, *args):
        pass
    

    和/或

    def method(self, **kwargs):
        pass
    

    取决于您如何使用参数(以及您希望如何调用函数)。

        3
  •  12
  •   ire_and_curses    16 年前

    I think the 'Pythonic' way of answering this is to look deeper than syntax. Passing in that many arguments to a method indicates a likely problem with your object model.

    1. 首先,您真的需要向这个方法传递这么多参数吗?也许这是一个迹象,表明这项工作可以在其他地方更好地完成(由一个已经可以访问变量的对象)?

    2. If this really is the best place for the method, then could some of those arguments be supplied as instance variables of this object itself (via self )?

    3. 如果没有,是否可以重新定义父对象的职责以包括它们?

    4. 如果不是,您是否可以将任何单个参数封装到一个复合对象中,从而形成它们之间的关系?如果任何一个论点有任何共同点,那么这应该是可能的。

        4
  •  1
  •   ooboo    16 年前

    If you have a function that takes so many variables as arguments, the last thing you have to worry about is indentation

        5
  •  1
  •   L̲̳o̲̳̳n̲̳̳g̲̳̳p̲̳o̲̳̳k̲̳̳e̲̳̳    16 年前

    我只是在79点被击中后就分裂到左括号,如下所示:

    def method(self, alpha, beta, gamma, delta, epsilon, zeta, eta, theta, iota,
               kappa):
    

    如果名字太长,放在左括号后,我会这样做:

    x.long_function_is_long(
        long_argument_is_loooooooooooooooooooooooooooooooooooooooong,
        longer_argument_is_looooooooooooooooooooooooooooooooooooooooonger
    )
    
        6
  •  -2
  •   CastleDweller    16 年前

    I usually do this, I don't know if it's the best, but it works. Since I have to split the line I make them equally longer (if I can):

    def method(self, alpha, beta, gamma, delta, epsilon, \
                     zeta, eta, theta, iota, kappa):
        pass
    

    另外,我建议使用与david相同数量的参数。 *args

    推荐文章