Skip to content

Instantly share code, notes, and snippets.

@xoxwgys56
Last active August 4, 2021 06:04
Show Gist options
  • Save xoxwgys56/a35b1206f8b547c25630e91d523a0e20 to your computer and use it in GitHub Desktop.
Save xoxwgys56/a35b1206f8b547c25630e91d523a0e20 to your computer and use it in GitHub Desktop.
python name mangling example with class
"""
Below value called `private` or `protected` is not accredited expression.
I choose those expression for easy to understand scope.
"""
class MyClass:
__private_value = 'private'
_protected_value = 'protected'
public_value = 'public'
def __init__(self, private='', protected='', public=''):
if private:
self.__private_value = private
if protected:
self._protected_value = protected
if public:
self.public_value = public
def print_private(self):
print(self.__private_value)
my_class = MyClass()
print(my_class.public_value)
print(my_class._protected_value)
my_class.print_private()
print(my_class.__private_value)
@xoxwgys56
Copy link
Author

Result

public
protected
private
Traceback (most recent call last):
  File "scope/private.py", line 22, in <module>
    print(my_class.__private_value)
AttributeError: 'MyClass' object has no attribute '__private_value'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment