# Square Class: Define a Square with private instance
class Square:
def __init__(self, size=0):
# initialise variables
self.__size = size
# Making attributes private
# Naming convention, when want to make attribute private, precede it with two underscores __
# e.g. self.__private_data. Then Python automatically renames it as _ClassName__private_date (name mangling)
# so instance.__private_data will not access this attribute
# but instance._PrivateClass__private_data will still be able to access it.
class PrivateClass:
"""Class with public and private attributes."""
def __init__(self):
"""Initialize the public and private attributes."""
self.public_data = "public" # public attribute
self.__private_data = "private" # private attribute
instance = PrivateClass()
instance.public_data
# 'public'
instance.__private_data
# AttributeError: 'PrivateClass' object has no attribute '__private_data'
instance._PrivateClass__private_data
# 'private'
instance._PrivateClass__private_data = 'modified'
instance._PrivateClass__private_data
# 'modified'