Consider a class Employee
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
emp_obj = Employee('Sam', 50000)
print(emp_obj.name, emp_obj.salary)
I tried to implement encapsulation in Python to restrict access to important data like salary. For this, I declared the variable salary as private by placing two underscores as the prefix. Also, I modified the above code by referring the second answer from the following link from StackOverflow: StackOverflow Link
class Employee:
def __init__(self, name, salary):
self.name = name
self.__salary = salary
@property
def salary(self):
return self.__salary
@salary.setter
def salary(self, salary):
self.__salary = salary
def getSalary(self):
return 'The Salary is {0}' .format(self.salary)
emp_obj = Employee('Sam', 50000)
print(emp_obj.name, emp_obj.salary)
print(emp_obj.getSalary())
I do not see any considerable difference.
So I modified the code again:
class Employee:
def __init__(self, name):
self.name = name
#self.__salary = salary
def setSalary(self, salary):
self.__salary = salary
def getSalary():
return salary
emp_obj = Employee('Sam')
emp_obj.setSalary(50000)
print(emp_obj.name)
print(emp_obj.getSalary)
The output I received was:
Sam
<bound method Employee.getSalary of <__main__.Employee object at 0x0000019E1B961A58>>
What does the above output mean? Clearly, my code did not work properly. I tried to set the salary by passing the value of salary as an argument. Kindly specify the error and the solution to solve the issue.
I also have another doubt - What do Python functions(methods) that start and end with underscores represent or convey?
def __init__(self):
The above command is used to initialize constructor in Python, which is called by default when an object of a class is created.
I am using Python 3.6.5.
The code was changed as per @ShadowRanger:
print(emp_obj.getSalary())
Then I received the following output with an error:
Sam
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-21-f115117b2a1c> in <module>()
13 emp_obj.setSalary(50000)
14 print(emp_obj.name)
---> 15 print(emp_obj.getSalary())
TypeError: getSalary() takes 0 positional arguments but 1 was given