Actual implementation of private variables in python class [duplicate]

让人想犯罪 __ 提交于 2019-12-24 02:56:28

问题


Possible Duplicate:
The meaning of a single- and a double-underscore before an object name in Python

I had a question when I was reading the python documentation on private variables link.

So the documentation tells that it is a convention to name private variables with an underscore but python does not make the field private.

>>> class a():
      def __init__(self):
         self.public = 11
         self._priv = 12
>>> b = a()
>>> print b._priv
>>> 12

I wanted to know if there is a way in which I can make a variable "truly" private in python.


回答1:


  • Guido van Rossum put it: we are all adults.
  • The extended version: We are all adults. Feel free to shoot yourself in the foot if you must.

You can hide it a bit if you must, but you really shoudn't:

class NonAdult(object):
    def __init__(self):
        self.__private_number = '42'
    def __getattr__(self, name):
        if name.startswith('__private'):
            raise AttributeError

if __name__ == '__main__':
    na = NonAdult()
    print(na.__private_number) # raises AttributeError
    print(na.__dict__['_NonAdult__private_number']) # would still return 42



回答2:


No, there are no private variables or methods in Python objects. The phrase "We're all consenting adults here" is generally used to explain that they are seen as unnecessary.

A single underscore is sometimes used for "private" members, buy only as a convention; it serves no functional purpose.

Leading double underscores cause name mangling, but are only intended to avoid naming collisions in subclasses. It does not provide any "private member safety", as you can still get to them.




回答3:


You can use a double leading underscore to invoke Pythons name mangling. So __priv becomes _MyClass__priv. It will still be accessible, but prevents subclasses from accidental overriding.



来源:https://stackoverflow.com/questions/14168791/actual-implementation-of-private-variables-in-python-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!