Python Practice › OOP Programs › Program 4

Class variables

EasyOOP Programs · 4 of 48

Write a Python class with a class variable shared by all objects.

Advertisement
Output
SQA Tools SQA Tools 2

Approach

  1. Define the variable in the class body; update it through the class name.

Solution

Python
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)
Output
SQA Tools SQA Tools 2

Line by line

Lines 2-3

Class variables are shared by every object.

Line 7

Updating through Employee.count changes the shared value; self.count += 1 would create a separate copy on that object instead.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More oop programs

← All 48 OOP Programs