Last active
May 4, 2020 13:21
-
-
Save tsuyukimakoto/55dbf4c12649db91dc1215f92b12b145 to your computer and use it in GitHub Desktop.
Python's private variable starts with dunder(double under) and not ends with dunder.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Spam: | |
def __init__(self): | |
self._var = "I'm under var" | |
self.__dunder_var = "I'm double under var" | |
def get_var(self): | |
return self._var | |
def get_dunder_var(self): | |
return self.__dunder_var | |
if __name__ == '__main__': | |
spam = Spam() | |
print('---- access to _var direct') | |
print(spam._var) | |
print('---') | |
print('---- access to __dunder_var direct') | |
try: | |
print(spam.__dunder_var) | |
except AttributeError: | |
print('AttributeError is raised when access to __dunder_var direct') | |
print('---') | |
print('---- access to _var using accessor') | |
print(spam.get_var()) | |
print('---') | |
print('---- access to __dunder_var using accessor') | |
print(spam.get_dunder_var()) | |
print('---') | |
""" | |
---- access to _var direct | |
I'm under var | |
--- | |
---- access to __dunder_var direct | |
AttributeError is raised when access to __dunder_var direct | |
--- | |
---- access to _var using accessor | |
I'm under var | |
--- | |
---- access to __dunder_var using accessor | |
I'm double under var | |
--- | |
>>> # just renamed from the outside, it doesn't mean it's inaccessible. | |
>>> spam.__dunder_var | |
Traceback (most recent call last): | |
File "<stdin>", line 1, in <module> | |
AttributeError: 'Spam' object has no attribute '__dunder_var' | |
>>> spam._Spam__dunder_var | |
"I'm double under var" | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment