PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
    • Python Exercises
    • C Programming Exercises
    • C++ Exercises
  • Quizzes
  • Code Editor
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
Home » Python » Python Object-Oriented Programming (OOP) » Python Class Variables

Python Class Variables

Updated on: September 8, 2023 | 8 Comments

In Python, class variables (also known as class attributes) are shared across all instances (objects) of a class. They belong to the class itself, not to any specific instance.

In Object-oriented programming, we use instance and class variables to design a Class.

In Class, attributes can be defined into two parts:

  • Instance variables: If the value of a variable varies from object to object, then such variables are called instance variables.
  • Class Variables: A class variable is a variable that is declared inside of a Class but outside of any instance method or __init__() method.

After reading this article, you’ll learn:

  • How to create and access class variables
  • Modify values of class variables
  • Instance variable vs. class variables
  • The behavior of a class variable in inheritance

Table of contents

  • What is Class Variable in Python?
  • Create Class Variables
  • Accessing Class Variables
    • Example 1: Access Class Variable in the constructor
    • Example 2: Access Class Variable in Instance method and outside class
  • Modify Class Variables
  • Class Variable vs. Instance variables
  • Class Variables In Inheritance
  • Wrong Use of Class Variables

What is Class Variable in Python?

If the value of a variable is not varied from object to object, such types of variables are called class or static variables.

All instances of a class share class variables. Unlike instance variable, the value of a class variable is not varied from object to object,

In Python, class variables are declared when a class is being constructed. They are not defined inside any method of a class. Because of this, only one copy of the static variable will be created and shared between all class objects.

For example, in the Student class, we can have different instance variables such as name and roll number because each student’s name and roll number are different.

But, if we want to include the school name in the student class, we must use the class variable instead of an instance variable because the school name is the same for all students. So, instead of maintaining a separate copy in each object, we can create a class variable that will hold the school name so all students (objects) can share it.

We can add any number of class variables in a class.