PYnative

Practice Coding

  • Python â–¼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Coding Exercises â–¼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • MCQsâ–¼
    • Python MCQ Quizzes
    • Java MCQ Quizzes
    • C++ MCQ Quizzes
  • Compilersâ–¼
    • Online Python Compiler
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » Python » Python Object-Oriented Programming (OOP) » Python Class Variables

Python Class Variables

Updated on: December 4, 2026 | 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.

A class can have two kinds of attributes:

  • 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
  • Be careful with mutable class variables
  • Practical example: count objects with a class variable
  • Summary

What is Class Variable in Python?

If the value of a variable is the same for every object of a class, it should be a class variable. Class variables are sometimes called static variables, as in languages like Java.

All instances of a class share class variables. Unlike an instance variable, a class variable has the same value for every object.

In Python, class variables are declared when a class is defined, directly in the class body and not inside any method. Because of this, only one copy of each class variable exists, and it is shared between all objects of the class.

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, a class variable is the better choice, 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.

Understand Class Variables
Understand Class Variables

Create Class Variables

A class variable is declared inside of a class, but outside of any instance method or __init__() method.

You can use the class name or the instance to access a class variable.

By convention, class variables are placed right below the class header, before the constructor and other methods.

Example:

class Student:
    # Class variable
    school_name = 'ABC School'
    
    def __init__(self, name, roll_no):
        self.name = name
        self.roll_no = roll_no

# create first object
s1 = Student('Emma', 10)
# access class variable using the class name
print(s1.name, s1.roll_no, Student.school_name)

# create second object
s2 = Student('Jessa', 20)
# access class variable using the object
print(s2.name, s2.roll_no, s2.school_name)
Code language: Python (python)

Output

Emma 10 ABC School
Jessa 20 ABC School

In the above example, we created the class variable school_name and accessed it using the object and class name.

Note: Like regular variables, class variables can store data of any type. We can use Python list, tuple, and dictionary as a class variable.

Accessing Class Variables

We can access class variables by class name or object reference, but it is recommended to use the class name.

In Python, you can access a class variable in the following places:

  • Access inside the constructor by using either self parameter or class name.
  • Inside an instance method, by using either self or the class name.
  • Access from outside of class by using either object reference or class name.

Example 1: Access Class Variable in the constructor

class Student:
    # Class variable
    school_name = 'ABC School'

    # constructor
    def __init__(self, name):
        self.name = name
        # access class variable inside constructor using self
        print(self.school_name)
        # access using class name
        print(Student.school_name)

# create Object
s1 = Student('Emma')Code language: Python (python)

Output

ABC School
ABC School

In this example, we accessed the class variable school_name using both the class name and the self parameter inside the constructor.

Example 2: Access Class Variable in Instance method and outside class

class Student:
    # Class variable
    school_name = 'ABC School'

    # constructor
    def __init__(self, name, roll_no):
        self.name = name
        self.roll_no = roll_no

    # Instance method
    def show(self):
        print('Inside instance method')
        # access using self
        print(self.name, self.roll_no, self.school_name)
        # access using class name
        print(Student.school_name)

# create Object
s1 = Student('Emma', 10)
s1.show()

print('Outside class')
# access class variable outside class
# access using object reference
print(s1.school_name)

# access using class name
print(Student.school_name)
Code language: Python (python)

Output

Inside instance method
Emma 10 ABC School
ABC School
Outside class
ABC School
ABC School

Modify Class Variables

Generally, you assign a value to a class variable in the class definition. However, you can change its value later, either inside the class or from outside of it.

Note: It is recommended to change the class variable’s value using the class name.

If you modify a class variable using an instance, it doesn’t change the class variable itself. Instead, it creates an instance variable with the same name that shadows (or hides) the class variable for that instance.

Example:

class Student:
    # Class variable
    school_name = 'ABC School'

    # constructor
    def __init__(self, name, roll_no):
        self.name = name
        self.roll_no = roll_no

    # Instance method
    def show(self):
        print(self.name, self.roll_no, Student.school_name)

# create Object
s1 = Student('Emma', 10)
print('Before')
s1.show()

# Modify class variable
Student.school_name = 'XYZ School'
print('After')
s1.show()Code language: Python (python)

Output:

Before
Emma 10 ABC School
After
Emma 10 XYZ School

Note:

It is best practice to use a class name to change the value of a class variable. Because if we try to change the class variable’s value by using an object, a new instance variable is created for that particular object, which shadows the class variables.

Example:

class Student:
    # Class variable
    school_name = 'ABC School'

    # constructor
    def __init__(self, name, roll_no):
        self.name = name
        self.roll_no = roll_no

# create Objects
s1 = Student('Emma', 10)
s2 = Student('Jessa', 20)

print('Before')
print(s1.name, s1.roll_no, s1.school_name)
print(s2.name, s2.roll_no, s2.school_name)

# Modify class variable using object reference
s1.school_name = 'PQR School'
print('After')
print(s1.name, s1.roll_no, s1.school_name)
print(s2.name, s2.roll_no, s2.school_name)Code language: Python (python)

Output:

Before
Emma 10 ABC School
Jessa 20 ABC School
After
Emma 10 PQR School
Jessa 20 ABC School

A new instance variable is created for the s1 object only, and it shadows the class variable. s2 and the class itself still see ‘ABC School’. So, always use the class name to modify a class variable.

Class Variable vs. Instance variables

Let’s compare instance variables and class variables side by side.

To recap the two kinds of attributes:

  • Instance variables: The instance variable’s value varies from object to object. Objects do not share instance variables. Every object has its copy of the instance attribute.
  • Class Variables: A class variable is a variable that is declared inside of a class but outside of any instance method or the __init__() method. Class variables are shared by all instances of a class.

Read More: Instance variables in Python with Examples. The following table shows the differences between instance and class variables.

Instance VariableClass Variable
Instance variables are not shared by objects. Every object has its own copy of the instance attribute. Class variables are shared by all instances.
Instance variables are usually created inside the constructor, i.e., the __init__() method, using self.Class variables are declared inside the class definition but outside any of the instance methods and constructors.
It gets created when an instance of the class is created.It is created when the class definition is executed, before any object exists.
Changes made to these variables through one object will not reflect in another object.Changes made to the class variable through the class name are reflected in all objects.
Class Variables vs. Instance Variables

Example:

Let’s see the example to create a class variable and instance variable.

class Car:
    # Class variable
    manufacturer = 'BMW'

    def __init__(self, model, price):
        # instance variable
        self.model = model
        self.price = price

# create Object
car = Car('x1', 2500)
print(car.model, car.price, Car.manufacturer)Code language: Python (python)

Output:

x1 2500 BMW

Class Variables In Inheritance

As you know, only one copy of the class variable will be created and shared between all objects of that class.

When we use inheritance, the child class can read all the class variables and methods of the base class.

But be careful when assigning: Student.course = ... creates a new class variable on the child class Student, and the parent’s value in Course.course stays unchanged. To change the value for the parent and every class that inherits it, assign through the parent class name: Course.course = ....

Example

class Course:
    # class variable
    course = "Python"

class Student(Course):

    def __init__(self, name):
        self.name = name

    def show_student(self):
        # Accessing class variable of parent class
        print('Before')
        print("Student name:", self.name, "Course Name:", Student.course)
        # this creates a new class variable on Student
        print('Now')
        Student.course = "Machine Learning"
        print("Student name:", self.name, "Course Name:", Student.course)

# creating object of Student class
stud = Student("Emma")
stud.show_student()

# the parent class still has its original value
print("Parent class course:", Course.course)Code language: Python (python)

Output

Before
Student name: Emma Course Name: Python
Now
Student name: Emma Course Name: Machine Learning
Parent class course: Python

What if both child and parent classes have the same class variable name? In this case, the child’s class variable overrides (shadows) the parent’s for the child class and its objects. The parent class keeps its own value, as the following example shows.

Example:

class Course:
    # class variable
    course = "Python"

class Student(Course):
    # class variable
    course = "SQL"

    def __init__(self, name):
        self.name = name

    def show_student(self):
        # Accessing class variable
        print('Before')
        print("Student name:", self.name, "Course Name:", Student.course)
        # changing class variable's value
        print('Now')
        Student.course = "Machine Learning"
        print("Student name:", self.name, "Course Name:", Student.course)

# creating object of Student class
stud = Student("Emma")
stud.show_student()

# parent class course name
print('Parent Class Course Name:', Course.course)Code language: Python (python)

Output:

Before
Student name: Emma Course Name: SQL
Now
Student name: Emma Course Name: Machine Learning
Parent Class Course Name: Python

Wrong Use of Class Variables

Use class variables carefully, because all objects share the same copy. A common mistake is to “modify” a class variable through an object. This doesn’t change the shared value at all. It silently creates an instance variable for that one object.

Example

class Player:
    # class variables
    club = 'Chelsea'
    sport = 'Football'

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

    def show(self):
        print("Player :", 'Name:', self.name, 'Club:', self.club, 'Sports:', self.sport)

p1 = Player('John')

# wrong use of class variable
p1.club = 'FC'
p1.show()

p2 = Player('Emma')
p2.sport = 'Tennis'
p2.show()

# actual class variable value
print('Club:', Player.club, 'Sport:', Player.sport)Code language: Python (python)

Output

Player : Name: John Club: FC Sports: Football
Player : Name: Emma Club: Chelsea Sports: Tennis
Club: Chelsea Sport: Football

In the above example, the instance variable name is unique for each player. The class variables club and sport can be read by any object.

When each object assigned to a class variable, Python created a new instance variable with the same name for that particular object, which shadows the class variable.

In our case, for object p1 new instance variable club gets created, and for object p2 new instance variable sport gets created.

So when you access these names through p1 or p2, you get the instance variable, not the actual class variable value.

To avoid this, always modify a class variable using the class name, so that all objects get the updated value:

Player.club = 'FC'
Player.sport = 'Tennis'Code language: Python (python)

Be careful with mutable class variables

If a class variable holds a mutable object, such as a list or dictionary, changing that object through any instance changes it for all instances. No new instance variable is created, because you’re modifying the shared object, not assigning a new value.

# wrong: one list shared by all dogs
class Dog:
    tricks = []

    def __init__(self, name):
        self.name = name

    def add_trick(self, trick):
        self.tricks.append(trick)

a = Dog("Buddy")
b = Dog("Max")
a.add_trick("roll over")
b.add_trick("sit")
print(a.tricks)  # ['roll over', 'sit']  (Max's trick appears too!)

# right: give each object its own list
class Dog:
    def __init__(self, name):
        self.name = name
        self.tricks = []  # instance variable

    def add_trick(self, trick):
        self.tricks.append(trick)

a = Dog("Buddy")
b = Dog("Max")
a.add_trick("roll over")
b.add_trick("sit")
print(a.tricks, b.tricks)  # ['roll over'] ['sit']Code language: Python (python)

Practical example: count objects with a class variable

A common use of a class variable is to keep data about the class as a whole, such as how many objects have been created. Increase the counter through the class name in the constructor:

class Employee:
    # class variable shared by all employees
    count = 0

    def __init__(self, name):
        self.name = name
        Employee.count += 1

Employee("Jessa")
Employee("Kelly")
Employee("Emma")
print("Total employees:", Employee.count)
# Output: Total employees: 3Code language: Python (python)

Tip: Inside a method, you can also use type(self).count instead of the class name, or a class method with cls.count. These work correctly with subclasses too.

Summary

  • A class variable is defined in the class body, outside any method, and is shared by all objects of the class.
  • You can read it using the class name or an object, but you should modify it only using the class name.
  • Assigning to a class variable through an object creates an instance variable that shadows it for that object only.
  • In inheritance, a child class can read the parent’s class variables. Assigning through the child’s name creates a separate variable on the child.
  • Avoid mutable class variables (lists, dicts) for per-object data. Use instance variables instead.

Filed Under: Python, Python Object-Oriented Programming (OOP)

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Object-Oriented Programming (OOP)

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes
In: Python Python Object-Oriented Programming (OOP)
TweetF  sharein  shareP  Pin

  Python OOP

  • Python OOP
  • Classes and Objects in Python
  • Constructors in Python
  • Python Destructors
  • Encapsulation in Python
  • Polymorphism in Python
  • Inheritance in Python
  • Python Instance Variables
  • Python Instance Methods
  • Python Class Variables
  • Python Class Method
  • Python Static Method
  • Python Class Method vs. Static Method vs. Instance Method
  • Python OOP exercise

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is a platform built to help developers learn by doing. Solve coding exercises, take MCQs, and run code directly in built-in online compilers.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

MCQ Quizzes

  • Python MCQs
  • Java MCQs
  • C++ MCQs

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com