Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simulate private variables in python [duplicate]

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."

like image 735
Cheery Avatar asked Jul 20 '10 22:07

Cheery


2 Answers

Private variables is covered in the Python documentation:

9.6. Private Variables

“Private” instance variables that cannot be accessed except from inside an object don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.

Summary: use an underscore before the name.

like image 194
Mark Byers Avatar answered Nov 04 '22 05:11

Mark Byers


From the Python docs:

“Private” instance variables that cannot be accessed except from inside an object don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.

like image 40
DrDee Avatar answered Nov 04 '22 04:11

DrDee