Python,在循环中初始化类属性

时间:2018-07-28 08:09:30

标签: python loops class instance

如何在循环中初始化类实例的属性?下面的示例说明了我想做什么。想象一个具有20到30个属性的类。必须有一种有效的方法来设置值。我需要在字典中更改班级属性吗?但这将是一个问题,因为在此示例中,我正在使用Django框架创建带有类的表。预先感谢!

class Foo():
    fieldA = float()
    fieldB = float()
    fieldC = float()
    fieldD = float()
    fieldE = float()
    fieldF = float()
    # several more field elements


def main():
    foo_instance = Foo()

    # open here excel file with openpyxl library
    wb = openpyxl.load_workbook(BASE_DIR + file, read_only=True, data_only=True)
    ws = wb['sheet1']


    # I would like to iterate through the instance 
    for i in range(1,20):
        foo.fieldA = float(ws['A{}'.format(i)]) #how to iterate through the attributes from foo instance?

    '''
        This is the inefficient way:
        foo.fieldA = float(ws['A1'])
        foo.fieldB = float(ws['A2'])
        foo.fieldC = float(ws['A3'])
        foo.fieldD = float(ws['A4'])
        foo.fieldE = float(ws['A5'])
        etc.
    '''

if __name__ == "__main__":
    main()

1 个答案:

答案 0 :(得分:0)

尝试将变量放入列表中并对其进行迭代。

my_list = [fieldA, fieldB] # and so on...

# Set an index
index = 0

# Iterate
for field in my_list:
    field = float(ws['A{}'.format(index)])
    index += 1 # Increment index each time

您甚至可以删除变量名称,仅使用my_list[0]my_list[1]等列表索引,但这取决于您的需求。