0

I wrote two code snippets here and I think they both do the job. However, I need to understand why one is better than the other.

This implementation doesn't leverage @property and I don't need it to since I can just use self in the Honda class for example.

class Car(ABC):
    def __init__(self, wheels: int, car_name: str):
        self.wheels = wheels
        self.car_name = car_name
    
    @abstractmethod
    def drive(self, driver):
        pass
    
class Honda(Car):
    
    def drive(self, driver):
        print(f'total wheels {self.wheels} and car name {self.car_name}')
        self.car_name = "Nice"
    
class Toyota(Car):
    
    def drive(self, driver):
        print(f'total wheels {self.wheels}')

    @property
    def fuel_type() -> FuelType:
        pass

This implementation however is slightly different but has a lot more code in general

class Car(ABC):

    @abstractmethod
    def __init__(self, wheels: int, car_name: str):
        self.wheels = wheels
        self.car_name = car_name

    @property
    @abstractmethod
    def wheels(self):
        pass

    @wheels.setter
    @abstractmethod
    def wheels(self, value):
        pass

    @abstractmethod
    def drive(self, driver):
        pass


class Honda(Car):

    def __init__(self, wheels, car_name):
        self.__wheels = wheels
        self.__car_name = car_name

    @property
    def wheels(self):
        return self.__wheels

    @wheels.setter
    def wheels(self, value):
        self.__wheels = value

    def drive(self):
        print(f'total wheels {self.__wheels} and car name {self.__car_name}')


Would love to understand the difference between these two. Is one of these an interface and the other an abstract class? Am I using one or the other incorrectly? or Both are valid I'm just using abstract classes as an interface in option 1?

  • 1
    The first one seems much more pythonic to me. What do you think you are gaining with the getter/setter code in the second that the first one doesn't give you? – Mark Nov 24 '21 at 01:20
  • 1
    I would use first because it shorter and more readable for me. Java programmers probably would prefer second version because they prefer getters/setters – furas Nov 24 '21 at 08:35
  • I agree, but I want to be able to explain why the pythonic version is better. – BeetleJuice Nov 24 '21 at 17:53

0 Answers0