Class variables
Write a Python class with a class variable shared by all objects.
SQA Tools SQA Tools 2
Approach
- Define the variable in the class body; update it through the class name.
Solution
class Employee: company = "SQA Tools" count = 0 def __init__(self, name): self.name = name Employee.count += 1 e1 = Employee("Asha")e2 = Employee("Ravi")print(e1.company, e2.company, Employee.count)SQA Tools SQA Tools 2
Line by line
Class variables are shared by every object.
Updating through Employee.count changes the shared value; self.count += 1 would create a separate copy on that object instead.
Learn the concept
New to this topic? Read the lesson, then come back.