是否可以在for循环中自动创建实例?(Python3)

时间:2017-10-29 22:56:58

标签: python-3.x oop instances m

问:是否可以在for循环中自动创建实例:

Main.py:

class board
{
public:
int x;
int y;
vector <vector <RectangleShape> > cBoard;

create(int,int);
void drawTile(RenderWindow &window, int, int);
};

board::create(int x, int y){
    cBoard = vector <vector <RectangleShape> >(x, vector< RectangleShape >
(y, tile()));
    int counter = 0;
    RectangleShape t;

    for(int i = 0; i < y; i++){
        counter = 0;
        if(i % 2 == 1){
            counter = 1;
                }
    for(int ii = 0; ii < x; ii++){
        if(counter % 2 == 0){
            t.setFillColor(Color::Red);
            cBoard.push_back(t);
            cout << "red";
            counter++;
        }
        else if(counter % 2 == 1){
            t.setFillColor(Color::Green);
            cBoard.push_back(t);
            cout << "green";
            counter++;
        }
    }
    cout << endl;
}
}

Car.py

from Car import Car

car_list = [
    ['red', 555, 123.04],
    ['black', 666, 203.04],
    ['green', 111, 23.04],
    ]

cars = Car()


new_car_list = []

for line in car_list:
    new_car_list.append(cars.foo(line))

输出:

class Car:
    def __init__(self):
        self.number = int()
        self.color = str()
        self.price = float()

    def foo(self, line):
        for attribute in line:
            if isinstance(attribute,int):
                self.number = attribute
            elif isinstance(attribute, str):
                self.color = attribute
            elif isinstance(attribute, float):
                self.price = attribute
        return self
  

111

     

111

     

111

正如您所看到的,我有一个具有某些属性的Car Class。 在我的主文件中,我有一张卡片列表。 我的目标是: 1)能够为每辆汽车创建一个实例,并将其附加到包含dict的新列表,当hey键是由程序生成的id号时,该值是汽车的实例。 最后,我希望能够通过使用dict的键来访问实例属性。

有可能吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

每次在for循环中都会更新并添加相同的Car对象 cars 。你可以这样做:

new_car_list = []

for line in car_list:
    car = Car()
    new_car_list.append(car.foo(line))