简体   繁体   English

是否可以将默认参数传递给 for 循环?

[英]Is it possible to pass default parameters to a for loop?

I have a __str__ method that takes some optional parameters (default is set to None).我有一个__str__方法,它带有一些可选参数(默认设置为 None)。 If these parameters are not specified, it returns a str that shows the full matrix.如果未指定这些参数,则返回一个显示完整矩阵的 str。 If the optional parameters are specified, it returns a partial matrix corresponding to those values.如果指定了可选参数,则返回与这些值对应的部分矩阵。

def __str__(self, starting_row=None, starting_col=None, nrows=3, ncols=3):
    # remove that final space
    string = ""
    for i in range(starting_row, nrows):
        for j in range(starting_col, ncols):
            string += str(self.get(i, j))
        string += "\n"
    return string

My code works if starting_row and starting_col are specified to integer values (eg starting_row=1 ).如果starting_rowstarting_col被指定为integer 值(例如starting_row=1 ),我的代码就可以工作。 However, if these values are not specified, since the default value is None, I am getting an error.但是,如果未指定这些值,由于默认值为 None,我会收到错误消息。

What would be the most pythonic way to specify a starting_row and starting_column of 0 ONLY IF the user does not specify the starting_row within the function parameters?仅当用户未在 function 参数中指定starting_row时,将starting_rowstarting_column指定为0 的最pythonic 方法是什么? Is there a way to do so in the for loop parameters?有没有办法在 for 循环参数中这样做?

Just change the default values for the parameters.只需更改参数的默认值即可。
This is because in your case, the default value None for starting_row has no meaning, according to you.这是因为在您的情况下,根据您的说法, starting_row的默认值None没有任何意义。 Since you want it to default to 0, then do just that.既然您希望它默认为 0,那么就这样做。

def __str__(self, starting_row=0, starting_col=0, nrows=3, ncols=3):
    string = ""
    for i in range(starting_row, nrows):
        for j in range(starting_col, ncols):
            string += str(self.get(i, j))
        string += "\n"
    return string

Pedantic note: String concatenation like that is expensive, because strings aren't mutable in python so you're essentially creating new strings in every step. Pedantic note:这样的字符串连接很昂贵,因为字符串在 python 中是不可变的,因此您实际上是在每个步骤中创建新字符串。 A better alternative would be to append those values to a list and then perform a join at the end.更好的选择是将 append 这些值添加到列表中,然后在最后执行连接。

Pedantic note2: Also, this most likely is a method belonging to your class(as you have a self in there), so perhaps a cleaner way to go about it would be to not have parameters at all for the __str__() and instead make use of instance attributes Pedantic note2:此外,这很可能是属于您的类的方法(因为您在那里有一个自我),因此对于 go 来说,关于它的一种更清洁的方法可能是根本没有__str__()的参数,而是让使用实例属性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM