我正在根据用户的输入创建类的 x 实例。请快速浏览一下我的代码:
class Cut:
def __init__(self, length, qty):
self.length = length
self.qty = qty
qty_cut_lengths = input("How many cutting lengths are there?")
cut_number = 1
while cut_number <= qty_cut_lengths:
self.length = input("What is the length of " + cut_number + "?")
self.qty = input("How many pieces will be needed?")
cut_number += 1
例如如果用户输入 10 ,我希望代码创建10个Cut类实例,每个实例具有相应的长度和数量。因此,对于第一个裁切而言,假设“客户”需要5块30英寸的材料。我想要cut1.length = 30,cut1.qty =5。那么,假设他们需要20块15英寸的材料。 cut2.length = 15,cut2.qty =20。依此类推...我想不出一种实现此目标的好方法。感谢您的提前帮助!
答案 0 :(得分:0)
输入长度/数量后,创建一个新的剪切
cut = new Cut(length, quantity)
并将它们存储在列表中
cuts = []
while (cut_number <= qty_cut_lengths):
... create cut as above...
cuts.append(cut)
答案 1 :(得分:0)
离解决方案不远。您只需要创建实例并进行一些转换:
class Cut:
def __init__(self, length, qty):
self.length = length
self.qty = qty
qty_cut_lengths = input("How many cutting lengths are there?")
cuts=[]
for cut_number in range(int(qty_cut_lengths)):
length = input("What is the length of cut n°" +str(cut_number+1)+"?")
qty = input("How many pieces will be needed?")
cuts.append(Cut(int(length),int(qty))) # instance creation and storage