如何将对象函数应用于对象列表

时间:2019-11-27 21:19:50

标签: python list function class object

我有以下代码:

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)
    list_of_products = [Product(height, radius, name) for (height, radius, name) in products]
    print(list_of_products)

在代码的前几行中,Cylinder类还具有其他功能:

        self.height = height ### defines the variables
        self.radius = radius

    def volume(self): ### the volume function
        return np.pi * np.power(self.radius,2) * self.height; ### just the equation of volume

    def area(self):
        return 2 * np.pi * (self.radius * self.height + np.power(self.radius,2)) ### eq. of surface area

    def baseArea(self):
        return np.pi * np.power(self.radius,2) ### equation of a circle, one base of the cylinder

    def lateralArea(self):
        return 2 * np.pi * self.radius * self.height ### equation of the lateral area

    def circumference(self):
        return 2 * np.pi * self.radius ### radius of a circle

代码工作正常。我的问题是,使用对象列表(产品类),是否有一种简单的方法来创建第二个列表,例如,使用“ objectname” .volume()。 list_of_products列表仅包含Product类的对象。如果可能,我想避免导入除numpy之外的任何内容。 真的很感谢您的帮助,如果这是一个初学者的问题,我感到抱歉,我只是其中的一段日子。

0 个答案:

没有答案