Python:一组门,可同时或分别涂装

Python: a set of doors that can be painted simultaneously or separately

我必须创建一个具有一组门的代码,它们可以被调用以同时或单独绘制。我已经成功地创建了代码,但我需要关于我需要添加哪些确切代码才能更改所有门的颜色的建议。

代码如下:

class Door:
    colour = 'brown'

    def __init__(self, number, status):
        self.number = number
        self.status = status

    @classmethod
    def knock(cls):
        print("Knock!")

    @classmethod
    def paint(cls, colour):
        cls.colour = colour

    def open(self):
        self.status = 'opened'

    def close(self):
        self.status = 'closed'


class Door2:
    colour = 'yellow'

    def __init__(self, number, status):
        self.number = number
        self.status = status

    @classmethod
    def knock(cls):
        print("Knock!")

    @classmethod
    def paint(cls, colour):
        cls.colour = colour

    def open(self):
        self.status = 'opened'

    def close(self):
        self.status = 'closed'


class Door3:
    colour = 'green'

    def __init__(self, number, status):
        self.number = number
        self.status = status

    @classmethod
    def knock(cls):
        print("Knock!")

    @classmethod
    def paint(cls, colour):
        cls.colour = colour

    def open(self):
        self.status = 'opened'

    def close(self):
        self.status = 'closed'


class Door4:
    colour = 'red'

    def __init__(self, number, status):
        self.number = number
        self.status = status

    @classmethod
    def knock(cls):
        print("Knock!")

    @classmethod
    def paint(cls, colour):
        cls.colour = colour

    def open(self):
        self.status = 'opened'

    def close(self):
        self.status = 'closed'


door1 = Door(1, 'closed')
door2 = Door2(2, 'closed')
door3 = Door3(1, 'closed')
door4 = Door4(2, 'closed')


print(door1.colour)
print(door2.colour)
print(door3.colour)
print(door4.colour)

现在的输出:

brown
yellow
green
red

门的颜色应该与其 open/closed 状态完全相同:一个实例属性。这样就无需为不同的颜色重复相同的 class 定义四次:

class Door:
    def __init__(self, number, status, color):
        self.number = number
        self.status = status
        self.color = color

    def knock(self):
        print('Knock!')

    def paint(self, color):
        self.color = color

    def open(self):
        self.status = 'opened'

    def close(self):
        self.status = 'closed'

现在只需列出门:

doors = [Door(1, 'closed', 'brown'), Door(2, 'closed', 'yellow'), ...]

然后循环绘制它们:

for door in doors:
    print(door.color)
    door.paint('red')
    print(door.color)