Last active
March 4, 2019 13:30
-
-
Save kateolenya/8e144ddb2239b69297c216b821c774a5 to your computer and use it in GitHub Desktop.
Testing encapsulation in Python3
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
#!/usr/bin/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" ) | |
self.__turn_on() | |
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 | |
my_phone.call() | |
# 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 | |
my_phone._Phone__turn_on() | |
# 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