首页 > 解决方案 > 通过从列表中引入值来创建类对象

问题描述

我创建了一个名为“My_c​​lass”的类,并创建了 4 个对象(obj1、obj2、obj3、obj4),如下所示。

class My_class:
    def __init__(self, att1, att2, att3, att4, att5, att6):
        self.att1 = att1
        self.att2 = att2
        self.att3 = att3
        self.att4 = att4
        self.att5 = att5
        self.att6 = att6

    def __repr__(self):

        return "The values of the attributes are ({}, {}, {}, {}, {}, {})".format(self.att1, self.att2, self.att3, self.att4,
                                                                                    self.att5, self.att6)

obj1 = My_class(1, 2, 3, 4, 5, 6)
print(obj1)

obj2 = My_class(10, 20, 30, 40, 50, 60)
print(obj2)

# Lets say that I have 3 lists and I want to create the objects from the values of the lists.

list3 = ['a', 'b', 'c', 'd', 'e', 'f']
list4 = [-1, -2, -3, -4, -5, -6]
list5 = [-10, -20, -30, -40, -50, -60]

obj3 = My_class(list3[0], list3[1], list3[2], list3[3], list3[4], list3[5])
print(obj3)

obj4 = My_class(list4[0], list4[1], list4[2], list4[3], list4[4], list4[5])
print(obj4)

这段代码的输出是:

The values of the attributes are (1, 2, 3, 4, 5, 6)
The values of the attributes are (10, 20, 30, 40, 50, 60)
The values of the attributes are (a, b, c, d, e, f)
The values of the attributes are (-1, -2, -3, -4, -5, -6)

我想使用以下结构创建具有 list5 值的 obj5:

obj5 = My_class('introduce somehow the 6 values of list5 here without having to manually write them seperated by comas')

这是一个使用 6 个属性的简单示例。这个想法是在有更多属性的情况下有一个紧凑而有效的方法来做到这一点。

谢谢

标签: pythonclassobjectconstructor

解决方案


这将做到:

obj5 = My_class(*list5)

推荐阅读