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

后端 未结 12 2133
不思量自难忘°
不思量自难忘° 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

    The phrase commonly used is "we're all consenting adults here". By prepending a single underscore (don't expose) or double underscore (hide), you're telling the user of your class that you intend the member to be 'private' in some way. However, you're trusting everyone else to behave responsibly and respect that, unless they have a compelling reason not to (e.g. debuggers, code completion).

    If you truly must have something that is private, then you can implement it in an extension (e.g. in C for CPython). In most cases, however, you simply learn the Pythonic way of doing things.

提交回复
热议问题