Search code examples
pythonstaticprivate

What does it mean for a private method to be only accessible from its own class in python?


I read that Private class methods can't be called from outside their class.

If I have a Car class with a private method __reset_odometer()

can I say:

import Car
Car turboCar = Car();
turboCar.__reset_odometer();

__reset_odometer() is defined inside the Car class. turboCar is an instance of the Car class. So why does calling the method turboCar.__reset_odometer() result in an accesss error?

I guess 'outside the class' is a term that I am not understanding, b/c a turboCar to me is not outside the class Car


Solution

  • Calling turboCar.__reset_odometer() will raise an exception since, even though the method is being called on a Car object, it is still outside the class definition. Think of it this way: you aren't inside the class, writing definitions of methods when you instantiate turboCar = Car().

    So you can still refer to __reset_odometer inside the class like so,

    class Car(object):
        def __init__(self):
            self.__odometer = 88800
            self.__reset_odometer()  # <-- call double underscore function
    
        def __reset_odometer(self):
            self.__odometer = 0
    
        def read_odometer(self):
            return self.__odometer
    

    And using turboCar works fine and the odometer has been reset,

    >>> turboCar = Car()
    >>> turboCar.read_odometer()
    0
    

    Of course, with Python there are no real private variables like in C++ and the like,

    >>> turboCar._Car__odometer = 9999
    >>> turboCar.read_odometer()
    9999
    >>> turboCar._Car__reset_odometer()
    >>> turboCar.read_odometer()
    0