Why are Python's 'private' methods not actually private?

后端 未结 12 2265
不思量自难忘°
不思量自难忘° 2020-11-22 02:50

Python gives us the ability to create \'private\' methods and variables within a class by prepending double underscores to the name, like this: __myPrivateMethod()

12条回答
  •  离开以前
    2020-11-22 02:53

    Similar behavior exists when module attribute names begin with a single underscore (e.g. _foo).

    Module attributes named as such will not be copied into an importing module when using the from* method, e.g.:

    from bar import *
    

    However, this is a convention and not a language constraint. These are not private attributes; they can be referenced and manipulated by any importer. Some argue that because of this, Python can not implement true encapsulation.

提交回复
热议问题