是否有更好的方法在列表中提供大量参数到数据类?



当试图将许多参数放入成员变量时,使用数据类确实会清理类,但我想知道是否有一种优雅的方法将参数放入类中,特别是像这样:

@dataclass
class Ship:
width: int
height: int
...

def get_ships():
...
def get_data(ship):
...
def main():
ships = []
for ship in get_ships():
ship_data: List[int] = get_data(ship)
ship = Ship(ship_data[0], ship_data[1], ship_data[2], ship_data[3],
ship_data[4], ship_data[5], ship_data[6], ship_data[7],
ship_data[8], ship_data[9], ship_data[10], ship_data[11],
ship_data[12], ship_data[13], ship_data[14], ship_data[15],
ship_data[16], ship_data[17], ship_data[18], ship_data[19],
ship_data[20], ship_data[21], ship_data[22], ship_data[23],
ship_data[24], ship_data[25], ship_data[26], ship_data[27],
ship_data[28], ship_data[29], ship_data[30], ship_data[31])
ships.append(ship)

ship_data列表本身作为参数传递到类中是很好的,但这需要在类端进行处理,以便将列表元素放入成员变量中,这会破坏数据类的优雅性。所以我想知道是否有更好的方法来加入这些参数,因为这段代码可以更短。

使用星号-

for ship in get_ships():
ship_data: List[int] = get_data(ship)
ship = Ship(*ship_data)

如果你只想从ship_data中得到32个元素,那么使用列表切片-

ship = Ship(*ship_data[:32])

只包含31个元素,并且忽略超过31个的元素。

最新更新