我有以下代码部分:
class Product(Cylinder): ### Creates a child class of Cylinder called Product
def __init__(self, height, radius, name): ### new class paramenter, we now have name
super().__init__(height, radius) ### inherits the previous initial viables, no need to rewrite.
self.name = name ### name is now a new parameter.
def objectName(self): ### new functions to return the name of the object
return self.name
#### The bit about csv spreadsheets
import csv ### imports the csv module
with open('shopping.csv') as csv_file: ### opens the csv file
reader = csv.reader(csv_file) ### defines the variable containing the information
next(csv_file) ### goes to the next line, ignoring the title
products = ["name","radius","hieght"] ### create's a base array for the information to be written to
for row in reader: ### for each row
products = np.vstack((products,row)); ### writes each row of the imported file to the array
products = np.delete(products, (0), axis=0) ### removes the non-useful information (row 0)
products[:,[0, 2]] = products[:,[2, 0]] ### switches first and third row to match our class and function inputs
print(products)
如图所示,共有三列,代码末尾分别是:高度、半径、名称。我需要能够将我创建的数组的每一行更改为以后可以在代码中使用的对象。我在代码开头导入了 numpy。如果可能的话,我想避免导入任何额外的模块。
打印时数组的内容:
[['30.0' '4.0' 'Pringles ']
['12.2' '3.3' 'Coke can']
['7.5' '4.1' "Cadbury's Hot Chocolate"]
['8.2' '3.2' 'Green Giant Sweetcorn']
['8.8' '11.8' 'Celebrations Tub']
['15.0' '0.8' 'Rowntrees Fruit Pastilles']
['13.0' '6.0' 'M&S Best Ginger Nuts Tub']
['17.0' '3.3' 'Monster Energy Drink']
['10.9' '3.8' 'Heinz Baked Beans']]
我需要一种使每一行成为对象的方法,例如:
pringles = Product(30.0,4.0,'Pringles')
cokeCan = Product(12.2,3.3,'Coke Can')
对象的名称不必是实际产品的名称,它可以是行号或此代码中最容易使用的任何名称。很感谢任何形式的帮助 :)