【问题标题】:Python, initialize class attribute in loopPython,在循环中初始化类属性
【发布时间】:2018-07-28 08:09: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()

【问题讨论】:

    标签: python loops class instance


    【解决方案1】:

    尝试将变量放在一个列表中并遍历它们。

    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] 等列表索引,但这取决于您的需要。

    【讨论】:

    • fieldA, fieldB 是一个类的属性。而且我也无法在类中生成列表,因为这不会在 Django 框架中创建表。我觉得我必须在类中创建一个函数来使属性可迭代。有没有更好的办法?
    • 我可以在列表中获取类的属性,但我不知道如何访问它:members = [attr for attr in dir(foo) if not callable(getattr(foo, attr))而不是 attr.startswith('__')]
    • @ErcanDogan 如果您可以控制该类,您也可以将列表设为该类的属性。此外,列表通常是迭代变量的首选方式。有一些方法可以做一些乱七八糟的事情,比如将带有递增数字的字符串转换为变量名,但我认为这不是好的做法。当您开始使用 Django 表时,无论如何您都可以轻松地从列表中提取变量,或者将列表作为参考传递。
    • @ErcanDogan 我相信你可以通过foo.__dict__.keys()访问实例的变量
    • 嗨,克里斯,foo.__dict__.keys() 为我提供了键字符串,并且只有那些声明为 self.xyz 而不是本地属性的字符串。
    猜你喜欢
    • 2017-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-04
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多