-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdataencapsulation.py
More file actions
52 lines (40 loc) · 1.75 KB
/
Copy pathdataencapsulation.py
File metadata and controls
52 lines (40 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# Demonstrating Data Encapsulation in Python
class Employee:
def __init__(self, name, salary):
# Private variables (Encapsulation)
# These variables are intended to be accessed only within the class
self.__name = name # Name is private
self.__salary = salary # Salary is private
# Public method to access private variable __name
def get_name(self):
return self.__name # Getter for name
# Public method to modify private variable __name
def set_name(self, name):
self.__name = name # Setter for name
# Public method to access private variable __salary
def get_salary(self):
return self.__salary # Getter for salary
# Public method to modify private variable __salary
def set_salary(self, salary):
if salary > 0:
self.__salary = salary # Setter for salary with validation
else:
print("Invalid salary!") # Salary can't be negative
# Creating an object of Employee class
emp = Employee("John", 50000)
# Accessing private variables using getter methods
print(emp.get_name()) # Output: John
print(emp.get_salary()) # Output: 50000
# Trying to modify private variables using setter methods
emp.set_name("Jane")
emp.set_salary(60000)
# Accessing the updated values
print(emp.get_name()) # Output: Jane
print(emp.get_salary()) # Output: 60000
# Trying to set an invalid salary
emp.set_salary(-100) # Output: Invalid salary!
## Encapsulation: Hiding data (variables) inside the class and restricting direct access from outside the
# class.
## Private Variables: Variables prefixed with __ to indicate they are private and should not be accessed
## directly.
## Getter and Setter Methods: Public methods used to access and modify private variables.