开发者

True privateness in Python

开发者 https://www.devze.com 2023-04-05 08:33 出处:网络
PEP 8 states that (emphasis mine): We don\'t use the term \"private\" here, since no attribute is really private in Python (without a generally unnecessary amount of work).

PEP 8 states that (emphasis mine):

We don't use the term "private" here, since no attribute is really private in Python (without a generally unnecessary amount of work).

I guess it refers to defining the actual class in some other language and then exposing only the public members to the interprete开发者_JAVA百科r. Is there some other way to achieve true privateness in Python?

I'm asking just out of curiosity.


No, nothing is truly private in Python.

If you know the method name, you can get it.

I think you might come up with a clever hack, but it would be just that - a hack. No such functionality exists in the language.


(Note: This is not "private" in the sense of C++/C#/Java type private, but it's close)

For a class, you can prefix a variable with '__'. This will cause Python to name mangle it so you can't accidentally call it from outside the class. For example:

class Test(object):
    def __init__(self):
        self.__number = 5

a = Test()
print a.__number # name error!

On the other hand, this isn't really private. You can access the number with:

print a.__Test_number

But it will prevent accidental mistakes, which is all private should be used for anyway. If it's prefixed with '__' and someone uses the code, their fault if that code breaks later on (they were warned).


There is no true privateness. The best you could do is obfuscate the variable name and then create getters/setters or properties.

The only way to achieve this that I can think of this is to read/write a file every time you need to have access to that variable.

You could also write a program in another language that will only respond to certain classes. Not sure how to go about doing this, though.

0

精彩评论

暂无评论...
验证码 换一张
取 消