dimanche 31 octobre 2021

What I can do better in this class? Python class refactoring

I have this code with some classes and the inheritance tree. What I can do better in this code? If we look in the direction of designing classes.

CAR_TYPES = {
    'Car': 'Car',
    'Truck': 'Truck',
    'SpecMachine': 'SpecMachine'
}


class CarBase:
    def __init__(self, brand, photo_file_name, carrying):
        self.car_type = None
        self.photo_file_name = photo_file_name
        self.brand = brand
        self.carrying = carrying

    def get_photo_file_ext(self):
        return self.photo_file_name.split(".")[-1]

    def __str__(self):
        return f"Car type: {self.car_type} | Brand: {self.brand} | Carrying: {self.carrying}"


class Truck(CarBase):
    def __init__(self, photo_file_name, brand, carrying, body_lwh):
        super().__init__(photo_file_name, brand, carrying)
        self.car_type = CAR_TYPES['Truck']
        self.body_lwh = body_lwh
        self.body_length = 0
        self.body_width = 0
        self.body_height = 0
        self.body_volume = 0

        if body_lwh:
            self._set_lwh()
            self._set_body_volume()

    def __str__(self):
        return f"{super().__str__()} | Length: {self.body_length} | Width: {self.body_width}, " \
           f"| Height {self.body_height}, | Volume: {self.body_volume}"

    def _set_lwh(self):
        try:
            self.body_length, self.body_width, self.body_height = map(float, self.body_lwh.split('x'))
        except ValueError:
            self.body_length, self.body_width, self.body_height = 0.0, 0.0, 0.0
            print("Value Error. Check your values and try again!")

    def _get_body_volume(self):
        return self.body_length * self.body_width * self.body_height

    def _set_body_volume(self):
        self.body_volume = self._get_body_volume()


class Car(CarBase):
    def __init__(self, photo_file_name, brand, carrying, passenger_seats_count):
        super().__init__(photo_file_name, brand, carrying)
        self.car_type = CAR_TYPES['Car']
        self.passenger_seats_count = passenger_seats_count

    def __str__(self):
        return f"{super().__str__()} | Passenger seats count: {self.passenger_seats_count}"


class SpecMachine(CarBase):
    def __init__(self, photo_file_name, brand, carrying, extra):
        super().__init__(photo_file_name, brand, carrying)
        self.car_type = CAR_TYPES['SpecMachine']
        self.extra = extra

    def __str__(self):
        return f"{super().__str__()} | Extra: {self.extra}"

I want to make this code more readable and more scalable, but I don't have any experience in this field and I want to learn it.

For example, what I can do with car_type variable? I tried to put car_type to CarBase class, but I don't know, how I can assign it later and to make it right from the design side

Aucun commentaire:

Enregistrer un commentaire