Pop Quiz #8.2 (Private Method/Variable)
- Due Mar 9, 2022 at 11:59pm
- Points 10
- Questions 7
- Available after Mar 9, 2022 at 1:30pm
- Time Limit None
- Allowed Attempts 2
Instructions
15.9. PRIVATE VARIABLES AND PRIVATE METHODS
- Most languages that define private variables do so through the use of the keyword “private” or something similar.
- The convention in Python is simpler, and it also makes it easier to immediately see what is private and what isn’t.
- Any method or instance variable whose name begins—but doesn’t end—with a double underscore (__) is private;
- anything else isn’t private.
- class A:
- __x = 1 # private
- __y__ = 2 # not private
- _z =3 # not private
- The mechanism used to provide privacy "mangles" the name of private variables and private methods when the code is compiled to bytecode.
- What specifically happens is that _classname is prepended to the variable name:
- The purpose is to prevent any accidental accesses.
- If someone wanted to, he could deliberately simulate the mangling and access the value.
- But performing the mangling in this easily readable form makes debugging easy.
- Private methods/variables cannot be created outside the class definition.
Only registered, enrolled users can take graded quizzes