I was just playing around to know more about encapsulation and found out that we cannot print out values that has been encapsulated, we have to define a seperate method that prints the value out, but here in my code i tried to print out an attribute of my class and it worked, so is there a mistake in my encapsulation?
code :
class Time:
timethytom = 'Best'
def __init__(self, hours, minutes):
self.__hours = hours
self.__minutes = minutes
def setTime(self,hour,minute):
self.__hours = hour
self.__minutes = minute
def getTime(self):
print(f'Time is {self.__hours}hr {self.__minutes}min')
def addTime(self, hour1, hour2, minute1, minute2):
print(f'{hour1+hour2} hours and {minute1+minute2} minutes')
time1 = Time(10, 20)
time1.setTime(20,5)
time1.hours = 55
time1.getTime()
print(time1.hours)
Thanks in advance :)
In Python, you can create a public variables in the class from out of the class, something like this:
class xyz:
pass
x = xyz()
x.y=10
print(x.y) #This will print 10
When you wrote this line time1.hours = 55
, actually you have created a variable named hours
in the object time1
which is not the same as the variable __hours
defined in the class.