神秘的Python表达

时间:2017-01-10 16:23:02

标签: python initialization generator

有人可以解释初始化mbr2的表达式吗?

class MyClass(object):
  def __init__(self, param1, param2=None):
    self.mbr1 = param1
    self.mbr2 = ({}, param2)[bool(param2)]

感谢。

3 个答案:

答案 0 :(得分:3)

逻辑从元组中选择两个值中的一个,具体取决于param1真实性。如果False元组的索引为0,则为1; bool很容易被强制转换成整数。

使用三元运算符可以更清楚地表达:

self.mbr2 = param2 if param2 else {}

或使用or

进行短路
self.mbr2 = param2 or {}

答案 1 :(得分:3)

执行以下操作是一种(奇怪的)方法:

self.mbr2 = param2 if param2 else {}

这更像是Pythonic。

如果({}, param2) truthy (1)或 falsy (0),它基本上会在元组(param2)上的两个元素之间进行选择(bool(param2)

答案 2 :(得分:0)

只要string groupValue = string.Empty; int rowSpanCount = 1; //change this to the column index that needs spanning int columnIndex = 6; protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { //check if the current row is a datarow if (e.Row.RowType == DataControlRowType.DataRow) { //get the current row number int currentRow = e.Row.DataItemIndex; //cast the current row to a datarowview DataRowView row = e.Row.DataItem as DataRowView; //check if the groupValue equals the current row, if so +1 rowspan in needed if (groupValue == row["myValue"].ToString()) { rowSpanCount++; } else if (currentRow > 1 && rowSpanCount > 1) { //apply rowspan to the first cell GridView1.Rows[currentRow - rowSpanCount].Cells[columnIndex].RowSpan = rowSpanCount; //remove the spanned rows for (int i = 1; i < rowSpanCount; i++) { GridView1.Rows[currentRow - (rowSpanCount - i)].Cells.RemoveAt(columnIndex); } //reset the rowSpanCount rowSpanCount = 1; } //set the groupValue variable for value comparison in the next row groupValue = row["myValue"].ToString(); } } 'truthy'param1。否则self.mbr2 = param1

注意:self.mbr2 = param1True == 1(以及False == 0会返回其中一个)。

更多的pythonic方式是:

bool