Practical 6: Program to Illustrate the Difference Between Public and Private Variables
Problem Statement
Write a Python program to illustrate the difference between public and private variables.
Solution Code
class Employee:
def __init__(self, name, salary):
self.name = name # Public variable
self.__salary = salary # Private variable
def display(self):
print(f"Name: {self.name}, Salary: {self.__salary}")
# Creating an object
emp1 = Employee("Alice", 5000)
# Accessing public and private variables
print(emp1.name) # Public variable
# print(emp1.__salary) # This will raise an error because __salary is private
emp1.display()
Output
The program should allow access to the public variable name and raise an error when trying to access the private variable __salary.
Example Output
Alice
Name: Alice, Salary: 5000
Process finished with exit code 0
Explanation
- Public Variable: name can be accessed directly from the object.
- Private Variable: __salary is prefixed with two underscores, making it private and inaccessible directly.
Key Concepts Learned
- Public and Private Variables
- Public variables can be accessed directly, while private variables are intended to be hidden and should be accessed using getter methods or within the class itself.