'is it possible to make a getter and a setter for all my member variables in a single function?

noob here trying to understand encapsulation. am i doing it right? my code is starting to become a little convoluted

class Car:
    def __init__(self, speed, color):
        self.__speed = speed
        self.__color = color

    @property
    def speed(self):
        return self.__speed

    @speed.setter
    def speed(self, speed):
        try:
            assert isinstance(speed, int), f"{speed}not a number"
        except AssertionError as e:
            print(e)
        else:
            self.__speed = speed

    @property
    def color(self):
        return self.__color

    @color.setter
    def color(self, color):
        try:
            assert isinstance(color, str), f"{color} is not a string"
        except AssertionError as e:
            print(e)
        else:
            self.__color = color


ford = Car(20, "green")

ford.speed = 40
print(ford.speed)

ford.color = 30
print(ford.color)

is it possible to make a getter and a setter for all my member variables in a single function?

or do i really have to set up a @property declarator and all its methods each time i want to encapsulate a variable in my class?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source