python - 如何使这个 Python 类定义代码不那么难看

标签 python idioms pyquery

编写类定义最惯用的方法是什么?我的以下代码不可能是执行此操作的最佳方法。

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()

[首先,python 是一种很棒的语言。这是我使用 Python 的第一个项目,我已经取得了可笑的进步。]

最佳答案

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))

这种方式避免了多次调用 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)

关于python - 如何使这个 Python 类定义代码不那么难看,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3192437/

相关文章:

Python:有效计算 Cadzow 滤波器的非对角线元素的平均值

python - 将输出文件从 Azure Batch 移动到 Data Lake

用于从索引到字符串末尾的子字符串的 Ruby 习语

c++ - 一个通用的 STLish contains()

python - 如何访问 PyQuery 查询中的第一项(或第 x 项)?

python - Flask:如何在 SQLAlchemy 中使用多个表

c++ - 类方法子集的延迟评估

python - 为什么这个未绑定(bind)的变量可以在 Python (pyquery) 中工作?

jquery - 使用python中的pyquery删除html中的所有隐藏元素

python - 连接失败后重新启动 Twisted-python Reactor