Reputation: 9869
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
Upvotes: 2
Views: 153
Reputation: 26397
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
Upvotes: 3
Reputation: 7951
You shouldn't use __ to mark method as private. You should use it only to protect methods from overriding. To mark method as private use _
In your example, the method name is actually turboCar._Car_reset_odometer cause that's the way Python is hiding methods that start with __.
You can find more info about differences between _ and __ here
Upvotes: 1
Reputation: 369094
class Car(object):
def __reset_odometer(self):
pass
def reset(self):
self.__reset_odometer() # This is valid.
turbocar = Car()
turbocar.reset()
turbocar.__reset_odometer() # This is invalid. __reset_odometer is only accessible from Car methods.
Upvotes: 2