Possible Duplicate:
private members in python
I've got few variables I really want to hide because they do not belong outside my class. Also all such non-documented variables render inheritance useless.
How do you hide such variables you don't want to show outside your object?
To clarify why I need private variables, first one example where inability to hide variables is just an inconvenience, then another that's really a problem:
class MyObject(object):
def __init__(self, length):
self.length = length
def __len__(self):
return length
item = MyObject(5)
item.length
len(item)
So I've got two ways to access 'length' of the item here. It's only an inconvenience and nothing horrible.
from wares import ImplementationSpecific
class MyThing(object):
def __init__(self):
self.__no_access_even_if_useful = ImplementationSpecific()
def restricted_access(self):
return self.__no_access_even_if_useful.mutable_value
thing = MyThing()
thing.restricted_access()
thing._MyThing__no_access_even_if_useful.something_useful_for_someone()
So say I want to change the implementation some day.. The chances are it'll break something unless I've really buried the implementation specifics.
I'll take it as anyone could program. That 'anyone' can find an useful thing from my implementation specifics and use it, even if I'd have strongly discouraged of doing so! It'd be much easier to just say: "no, it's not there, try something else."