Practical 1: Program to access a class variable using a class object.
Problem Statement
Write a Python program to access a class variable using a class object.
Solution Code
class Employee:
company_name = "TechCorp" # Class variable
# Creating an object of the Employee class
emp1 = Employee()
# Accessing class variable using object
print(f"Company Name: {emp1.company_name}")
Output:
The program should display the class variable company_name using the class object emp1.
Example Output
Company Name: TechAmplifiers
Process finished with exit code 0
Explanation
Below is the explanation of F.E. PPS Unit 5 Practical 1 solution where we have written Python program to access a class variable using a class object.
- Class Variable: company_name is a class variable shared by all instances of the class.
- The class variable is accessed via the class object emp1.
Key Concepts Learned
- Class Variables
- Class variables are shared by all objects of the class.
- Accessing Class Variables Using Object
- Even though class variables are associated with the class, they can be accessed through an object.