Search code examples
pythonidiomspyquery

How to make this Python class definition code less ugly


What's the most idiomatic way to write a class definition? There's no way that my code below is the best way to do this.

class Course:

    crn =  course =  title =  tipe =  cr_hours =  seats =  instructor =  days =  begin =  end = location = exam = ""

    def __init__(self, pyQueryRow):
        self.crn = Course.get_column(pyQueryRow, 0)
        self.course = Course.get_column(pyQueryRow, 1)
        self.title = Course.get_column(pyQueryRow, 2)
        self.tipe = Course.get_column(pyQueryRow, 3)
        self.cr_hours = Course.get_column(pyQueryRow, 4)
        self.seats = Course.get_column(pyQueryRow, 5)
        self.instructor = Course.get_column(pyQueryRow, 6)
        self.days = Course.get_column(pyQueryRow, 7)
        self.begin = Course.get_column(pyQueryRow, 8)
        self.end = Course.get_column(pyQueryRow, 9)
        self.location = Course.get_column(pyQueryRow, 10)
        self.exam = Course.get_column(pyQueryRow, 11)

    def get_column(row, index):
        return row.find('td').eq(index).text()

[First of all python is an awesome language. This is my first project using python and I've made a ridiculous amount of progress already.]


Solution

  • def__init__(self, pyQueryRow):
        for i,attr in enumerate("crn course title tipe cr_hours seats instructor"
                                " days begin end location exam".split()):
            setattr(self, attr, self.get_column(pyQueryRow, i))
    

    This way avoids multiple calls to self.get_column

    def__init__(self, pyQueryRow):
        attrs = ("crn course title tipe cr_hours seats instructor"
                 " days begin end location exam".split())
        values = [td.text for td in pyQueryRow.find('td')]
        for attr, value in zip(attrs, values):
            setattr(self, attr, value)