[Python] How can I pass a class type into a method and use it to create new objects of the...

Discussão em 'Python' iniciado por Stack, Agosto 6, 2025.

  1. Stack

    Stack Membro Participativo

    I have a situation where I have multiple csv files that I want to transform into various objects. So I have something like:

    #What works
    car = []
    with open("car.csv") as csv_file:
    data = iter(csv.reader(csv_file))
    next(data) # Discard header
    for row in data:
    car.append(Car(row[0], row[1], row[2])

    #What I want to do
    car = load("car.csv", Car.__class__)

    def load(file, cls):
    arr = []
    with open(file) as csv_file:
    data = iter(csv.reader(csv_file))
    next(data) # Discard header
    for row in data:
    arr.append(cls.__init__(row)) #Should make a new object
    return arr


    So then I could use load with Car, Boat, Graph, etc. As long as I pass in an orderly list that can satisfy the init function.

    Continue reading...

Compartilhe esta Página