mercredi 20 janvier 2021

Builder Pattern with @property

I want to use the Builder Pattern to construct a computer, there must be something I am doing slightly wrong because I am getting an error when I invoke the print(computer) line. When I remove that line the code works. I want to output the computer to the console but I cannot get it to work.

class Computer:
    def __init__(self, serial_number):
        self.serial = serial_number
        self.memory = None  # in gigabytes
        self.hdd = None
        self.gpu = None

    def __str__(self):
        info = ('Memory: {}GB'.format(self.memory),
                'Hard Disk: {GB}'.format(self.hdd),
                'Graphics Card: {}'.format(self.gpu))
        return '\n'.join(info)


class ComputerBuilder:
    def __init__(self):
        self.computer = Computer('AG123')

    def configure_memory(self, amount):
        self.computer.memory = amount

    def configure_hdd(self, amount):
        self.computer.hdd = amount

    def configure_gpu(self, gpu_model):
        self.computer.gpu = gpu_model


class HardwareEngineer:
    def __init__(self):
        self.builder = None

    def construct_computer(self, memory, hdd, gpu):
        self.builder = ComputerBuilder()
        [step for step in (self.builder.configure_memory(memory),
                           self.builder.configure_hdd(hdd),
                           self.builder.configure_gpu(gpu))]
    @property
    def computer(self):
        return self.builder.computer

def main():
    engineer = HardwareEngineer()
    engineer.construct_computer(hdd=1000,memory=64,gpu='GeForce RTX 3080')
    computer = engineer.computer
    print(computer)

if __name__ == '__main__':
    main()

The error I am receiving is the following:

Traceback (most recent call last):
  File "/Users/imac/PycharmProjects/pythonProject2/computer-builder.py", line 49, in <module>
    main()
  File "/Users/imac/PycharmProjects/pythonProject2/computer-builder.py", line 46, in main
    print(computer)
  File "/Users/imac/PycharmProjects/pythonProject2/computer-builder.py", line 10, in __str__
    'Hard Disk: {GB}'.format(self.hdd),
KeyError: 'GB'

Aucun commentaire:

Enregistrer un commentaire