Search code examples
pythonpolymorphismencapsulation

How exactly does Encapsulation via Data Hiding Work in Python? Beginner


I'm covering a section of Python on Class Polymorphism, specifically Encapsulation and Data Hiding.

The Example of such an Encapsulation is:

class Car:

    __maxspeed = 0
    __name = ""

    def __init__(self):
        self.__maxspeed = 200
        self.__name = "Corolla"

    def drive(self):
        print("Max speed is: " + str(self.__maxspeed))

    def setMaxSpeed(self,speed):
        self.__maxspeed = speed

car_a = Car()
car_a.drive()
car_a.setMaxSpeed(320)
car_a.drive()

The line car_a.drive() leads us to print("Max speed is: " + str(self.__maxspeed)). Where does the value for this specific self__maxspeed come from and why?

From the output, I see it's 200. And the output of car_a.setMaxSpeed(320) is 320. So the same question here with 320. And lastly, what's the function of __maxspeed = 0 and __nane = ""?

Sorry for the extensive question. I new to Python and these examples confused me. I greatly appreciate all help and time.


Solution

  • Where does the value (200) for this specific self__maxspeed come from and why?

    It comes from the __init__ method, which is invoked when you call Car():

    self.__maxspeed = 200
    

    Any time you create a Car it will have a maxspeed of 200 until you set it to something else.

    And the output of car_a.setMaxSpeed(320) is 320. So the same question here with 320.

    Here's the setMaxSpeed function:

    def setMaxSpeed(self,speed):
        self.__maxspeed = speed
    

    As you can see, it takes whatever you pass as the argument (320) and sets self.__maxspeed to it. Nothing too mysterious about it. That Car will now have a maxspeed of 320 until you set it to something else.

    lastly, what's the function of __maxspeed = 0 and __name = ""

    They don't have any function. That is to say, your code never uses them for anything, so either their presence is a mistake, or you have some other code that does something with them, but based on the code you've presented, they are useless and you could delete them with no ill effects.