[Tutor] Public, private and protected member variables.
Marc Barry
marc_barry at hotmail.com
Fri Oct 17 11:54:54 EDT 2003
Dear All:
I have a question regarding the existence of protected members in Python.
Basically, in a language like Java we have public, private and protected
member variables. But in Python I only know of public and private. I would
like to inherit from a class and be able to modify parent member variables,
but I would not like any class that doesn't inherit from the parent to be
able to modify the member variables (i.e. Protected concept in Java).
Here is a simple example:
#------------------------------------------------------------
class Car:
def __init__(self, colour):
self.__colour = colour
class Ferrari(Car):
def __init__(self, model, colour):
Car.__init__(self, colour)
self.__model = model
def printColour(self):
print self.__colour
a_ferrari = Ferrari("Enzo", "Red")
print dir(a_ferrari)
a_ferrari.printColour()
#------------------------------------------------------------
The output from running this script is:
['_Car__colour', '_Ferrari__model', '__doc__', '__init__', '__module__',
'printColour']
Traceback (most recent call last):
File "inheritance.py", line 19, in ?
a_ferrari.printColour()
File "inheritance.py", line 15, in printColour
self.__colour
AttributeError: Ferrari instance has no attribute '_Ferrari__colour'
As you can see the __colour member variable of Car is not visible in the
Ferrari class since it appears that appending '__' on a variable makes it
private and not protected. Is there a way to make a variable protected in
Python?
If I expose a variable in Car as public ,then I will allow users of the
class to modify it directly. I would like to avoid this since that fixes my
implementation to being always having to provide a variable named "colour"
for example. Also, this is just a simplification of my problem as my class
is much more complicated with a lot of gettable and settable properties in
the parent object (Which I want to inherit).
Regards,
Marc Barry
marc_barry at hotmail.com
_________________________________________________________________
MSN 8 with e-mail virus protection service: 2 months FREE*
http://join.msn.com/?page=features/virus
More information about the Tutor
mailing list