F.E. PPS Unit 5 Practical 6 solution

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

Below is the explanation of F.E. PPS Unit 5 Practical 6 solution where we have written Python program to illustrate the difference between public and private variables.

  • 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.
Tech Amplifier Final Logo
No content is added yet.