simulate private variables in python [duplicate]

2019-02-23 10:54发布

问题:

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

回答1:

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.



回答2:

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.