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

Time:11-10

I have to create a code that has set of doors and they can be called to be painted simulateneously or seperately. I have managed to create the code but I need advice on what exact code I need to add in order to change all of the door's colour.

Here is the code:

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)

The output right now:

brown
yellow
green
red

CodePudding user response:

The door colour should be exactly the same kind of thing as its open/closed status: an instance attribute. That eliminates the need to repeat the same class definition four times just for the different colours:

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'

Now just make a list of doors:

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

Then paint them all in a loop:

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