Skip to content

Instantly share code, notes, and snippets.



Last active Mar 4, 2019
What would you like to do?
Testing encapsulation in Python3
class Phone:
username = "Kate" # public variable
__serial_number = "11.22.33" # private variable
__how_many_times_turned_on = 0 # private variable
def __init__(self): # constructor
print( "The Phone object was created" )
def call(self): # public method
print( "Ring-ring!" )
def __turn_on(self): # private method
self.__how_many_times_turned_on += 1
print( "Times was turned on: ", self.__how_many_times_turned_on )
# initializing class object
my_phone = Phone()
print( "Testing public access to public data" )
# calling public method
# printing public variable
print( "The username is ", my_phone.username )
print( "Testing public access to private data" )
Trying to run private method as public method won't work:
my_phone.turn_on() - No
my_phone.__turn_on() - No again
However, gaining access through calling class will succeed
# calling private method
# printing private variable
print( "The serial number is ", my_phone._Phone__serial_number )
# modifying private variable
my_phone._Phone__serial_number = "44.55.66"
print( "New serial number is ", my_phone._Phone__serial_number )
input( "Press Enter to exit" )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.