F.E. PPS Unit 5 Practical 4 solution

Practical 4: Program to Differentiate Between Class and Object Variables

Problem Statement

Write a Python program to differentiate between class variables and object variables.

Solution Code

				
					class Employee:
    company_name = "TechCorp"  # Class variable

    def __init__(self, name):
        self.name = name  # Object variable

# Creating objects
emp1 = Employee("Alice")
emp2 = Employee("Bob")

# Accessing class and object variables
print(f"Emp1 Name: {emp1.name}, Company: {emp1.company_name}")
print(f"Emp2 Name: {emp2.name}, Company: {emp2.company_name}")

				
			

Output

The program should show the difference between class and object variables by accessing them using the objects.

Example Output

				
					Emp1 Name: Alice, Company: TechAmplifiers
Emp2 Name: Bob, Company: TechAmplifiers
Process finished with exit code 0
				
			

Explanation

  • Class Variable: company_name is shared among all instances of the class.
  • Object Variable: name is unique to each object (emp1, emp2).

Key Concepts Learned

  • Class vs Object Variables
    • Class variables are shared across all instances, while object variables are specific to each instance.
Tech Amplifier Final Logo