Python class variables are variables declared inside a class but outside any instance method or __init__() method. They are shared among all instances of the class, meaning a single copy exists and is accessible via the class name or any instance.

  • Declaration: Defined at the class level, typically placed just below the class header.

  • Access: Can be accessed using ClassName.variable_name or instance.variable_name.

  • Shared State: Changes to a class variable via the class name affect all instances.

  • Use Cases: Ideal for constants, counters (e.g., tracking total instances), default configurations, or shared data (e.g., school name in a Student class).

Example:

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

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

s1 = Student("Emma")
s2 = Student("Jessa")
print(s1.school_name)  # Output: ABC School
print(s2.school_name)  # Output: ABC School
Student.school_name = "XYZ School"
print(s1.school_name)  # Output: XYZ School (updated for all instances)

Important: Modifying a class variable through an instance creates an instance variable with the same name, hiding the class variable for that instance. Always use the class name to modify class variables.

Inheritance: Derived classes inherit class variables from their base class and can access or override them.

This is because of the way Python resolves names with the .. When you write self.list the Python runtime tries to resolve the list name first by looking for it in the instance object, and if it is not found there, then in the class instance.

Let's look into it step by step

self.list.append(1)
  1. Is there a list name into the object self?
    • Yes: Use it! Finish.
    • No: Go to 2.
  2. Is there a list name into the class instance of object self?
    • Yes: Use it! Finish
    • No: Error!

But when you bind a name things are different:

self.list = []
  1. Is there a list name into the object self?
    • Yes: Overwrite it!
    • No: Bind it!

So, that is always an instance variable.

Your first example creates a list into the class instance, as this is the active scope at the time (no self anywhere). But your second example creates a list explicitly in the scope of self.

More interesting would be the example:

class testClass():
    list = ['foo']
    def __init__(self):
        self.list = []
        self.list.append('thing')

x = testClass()
print x.list
print testClass.list
del x.list
print x.list

That will print:

['thing']
['foo']
['foo']

The moment you delete the instance name the class name is visible through the self reference.

Answer from rodrigo on Stack Overflow
🌐
Python documentation
docs.python.org › 3 › tutorial › classes.html
9. Classes — Python 3.14.3 documentation
As is true for modules, classes partake of the dynamic nature of Python: they are created at runtime, and can be modified further after creation. In C++ terminology, normally class members (including the data members) are public (except see below Private Variables), and all member functions ...
🌐
DigitalOcean
digitalocean.com › community › tutorials › understanding-class-and-instance-variables-in-python-3
Understanding Class and Instance Variables in Python 3 | DigitalOcean
August 20, 2021 - Defined outside of all the methods, class variables are, by convention, typically placed right below the class header and before the constructor method and other methods. Info: To follow along with the example code in this tutorial, open a Python interactive shell on your local system by running the python3 command.
People also ask

What is a class variable in Python?
A class variable is a variable that is defined within a class and is shared among all instances of that class. It can be accessed using the class name or an instance of the class.
🌐
ituonline.com
ituonline.com › itu online › blogs › python class variables: declaration, usage, and practical examples
Python Class Variables: Declaration, Usage, And Practical Examples ...
How do you define a class variable in Python?
You can define a class variable by declaring it inside the class but outside of any method, using the syntax variable_name = value.
🌐
ituonline.com
ituonline.com › itu online › blogs › python class variables: declaration, usage, and practical examples
Python Class Variables: Declaration, Usage, And Practical Examples ...
What is a Python namespace?

A Python namespace is a mapping from names to objects, with the property that there is zero relation between names in different namespaces. Namespaces are usually implemented as Python dictionaries, although this is abstracted away.

🌐
toptal.com
toptal.com › developers › python › python-class-attributes-an-overly-thorough-guide
Python Class Attributes: Examples of Variables | Toptal®
🌐
PYnative
pynative.com › home › python › python object-oriented programming (oop) › python class variables
Python Class Variables With Examples – PYnative
September 8, 2023 - Class Variables: A class variable is a variable that is declared inside of a class but outside of any instance method or init() method. Class variables are shared by all instances of a class. Read More: Instance variables in Python with Examples
Top answer
1 of 4
65

This is because of the way Python resolves names with the .. When you write self.list the Python runtime tries to resolve the list name first by looking for it in the instance object, and if it is not found there, then in the class instance.

Let's look into it step by step

self.list.append(1)
  1. Is there a list name into the object self?
    • Yes: Use it! Finish.
    • No: Go to 2.
  2. Is there a list name into the class instance of object self?
    • Yes: Use it! Finish
    • No: Error!

But when you bind a name things are different:

self.list = []
  1. Is there a list name into the object self?
    • Yes: Overwrite it!
    • No: Bind it!

So, that is always an instance variable.

Your first example creates a list into the class instance, as this is the active scope at the time (no self anywhere). But your second example creates a list explicitly in the scope of self.

More interesting would be the example:

class testClass():
    list = ['foo']
    def __init__(self):
        self.list = []
        self.list.append('thing')

x = testClass()
print x.list
print testClass.list
del x.list
print x.list

That will print:

['thing']
['foo']
['foo']

The moment you delete the instance name the class name is visible through the self reference.

2 of 4
10

Python has interesting rules about looking up names. If you really want to bend your mind, try this code:

class testClass():
    l = []
    def __init__(self):
        self.l = ['fred']

This will give each instance a variable called l that masks the class variable l. You will still be able to get at the class variable if you do self.__class__.l.

The way I think of it is this... Whenever you do instance.variable (even for method names, they're just variables who's values happen to be functions) it looks it up in the instance's dictionary. And if it can't find it there, it tries to look it up in the instance's class' dictionary. This is only if the variable is being 'read'. If it's being assigned to, it always creates a new entry in the instance dictionary.

🌐
GeeksforGeeks
geeksforgeeks.org › python › g-fact-34-class-or-static-variables-in-python
Class (Static) and Instance Variables in Python - GeeksforGeeks
2 weeks ago - Class variables are shared by all objects of a class, whereas instance variables are unique to each object. Unlike languages such as Java or C++, Python does not require a static keyword.
🌐
IONOS
ionos.com › digital guide › websites › web development › python class variables
How to create and use Python class variables
July 15, 2024 - Python class variables are variables that keep the same value for every instance of a class. We’ll go over their syntax and different ways you can use them.
🌐
CBT Nuggets
cbtnuggets.com › blog › technology › programming › python-class-variables-explained
Python Class Variables: Explained
May 9, 2023 - Here is a good way to sum up the relationship: a class variables is shared by all objects that are created. An instance of the class variable is always created on each newly minted object; it overrides the class instance. Lastly, an instance variable is only accessible to the object it was defined in. Warning: The following code will only work in Python 3.x
Find elsewhere
🌐
Python.org
discuss.python.org › python help
Class variables - Python Help - Discussions on Python.org
August 14, 2022 - Hi, I am confused about class variable and instance variable in below example: class Classy: varia = 2 def method(self): print(self.varia, self.var) obj = Classy() obj.var = 3 obj.method() Don’t we access class …
🌐
ITU Online
ituonline.com › itu online › blogs › python class variables: declaration, usage, and practical examples
Python Class Variables: Declaration, Usage, And Practical Examples - ITU Online IT Training
August 3, 2023 - Class variables in Python are powerful tools for sharing data among class instances. By declaring class variables within the class scope, developers can access and modify shared information easily.
🌐
Toptal
toptal.com › developers › python › python-class-attributes-an-overly-thorough-guide
Python Class Attributes: Examples of Variables | Toptal®
January 16, 2026 - If a Python class variable is set by accessing an instance, it will override the value only for that instance. This essentially overrides the class variable and turns it into an instance variable available intuitively only for that instance.
🌐
Career Karma
careerkarma.com › blog › python › python class variables vs. instance variables
Python Class Variables vs. Instance Variables | Career Karma
December 1, 2023 - Python class variables are defined within a class constructor and have the same value across all instances of a class. On Career Karma, learn how to use Python class and instance variables.
🌐
Python Tutorial
pythontutorial.net › home › python oop › python class variables
Python Class Variables Explained
March 31, 2025 - AttributeError: type object 'HtmlDocument' has no attribute 'media_type'Code language: Python (python) Another way to get the value of a class variable is to use the getattr() function. The getattr() function accepts an object and a variable name. It returns the value of the class variable.
Top answer
1 of 2
772

Neither way is necessarily correct or incorrect, they are just two different kinds of class elements:

  • Elements outside the __init__ method are static elements; they belong to the class.
  • Elements inside the __init__ method are elements of the object (self); they don't belong to the class.

You'll see it more clearly with some code:

class MyClass:
    static_elem = 123

    def __init__(self):
        self.object_elem = 456

c1 = MyClass()
c2 = MyClass()

# Initial values of both elements
>>> print c1.static_elem, c1.object_elem 
123 456
>>> print c2.static_elem, c2.object_elem
123 456

# Nothing new so far ...

# Let's try changing the static element
MyClass.static_elem = 999

>>> print c1.static_elem, c1.object_elem
999 456
>>> print c2.static_elem, c2.object_elem
999 456

# Now, let's try changing the object element
c1.object_elem = 888

>>> print c1.static_elem, c1.object_elem
999 888
>>> print c2.static_elem, c2.object_elem
999 456

As you can see, when we changed the class element, it changed for both objects. But, when we changed the object element, the other object remained unchanged.

2 of 2
25

I think this sample explains the difference between the styles:

james@bodacious-wired:~$cat test.py 
#!/usr/bin/env python

class MyClass:
    element1 = "Hello"

    def __init__(self):
        self.element2 = "World"

obj = MyClass()

print dir(MyClass)
print "--"
print dir(obj)
print "--"
print obj.element1 
print obj.element2
print MyClass.element1 + " " + MyClass.element2
james@bodacious-wired:~$./test.py 
['__doc__', '__init__', '__module__', 'element1']
--
['__doc__', '__init__', '__module__', 'element1', 'element2']
--
Hello
World
Traceback (most recent call last):
  File "./test.py", line 17, in <module>
    print MyClass.element2
AttributeError: class MyClass has no attribute 'element2'

element1 is bound to the class, element2 is bound to an instance of the class.

🌐
Syntaxdb
syntaxdb.com › ref › python › class-variables
Class and Instance Variables in Python - SyntaxDB - Python Syntax Reference
Used declare variables within a class. There are two main types: class variables, which have the same value across all class instances (i.e. static variables), and instance variables, which have different values for each object instance.
🌐
Digis
digiscorp.com › understanding-python-class-variables-a-beginners-guide
Understanding Python Class Variables: A Beginner's Guide
July 22, 2025 - If you assign a new value to a class variable using an instance, Python will create an instance variable instead — shadowing the class variable.
🌐
Fylehq
stories.fylehq.com › p › demystifying-class-variables-in-python-722
Demystifying Class Variables In Python - by Kirti - Fyle Stories
November 17, 2022 - Class variables are those variables which are independent of the object they are accessed from.
🌐
Dive into Python
diveintopython.org › home › learn python programming › classes in python › class variables, attributes, and properties
Class Variables and Properties in Python: Public, Private and Protected
May 3, 2024 - Properties: A property is a way to define a method as an attribute. Properties are created using the @property decorator. In Python, class variables are a powerful way to share data among all instances of a class.
🌐
DevGenius
blog.devgenius.io › how-to-use-class-variables-in-python-de5c4e511dca
How to Use Class Variables in Python | by A.I Hub | Dev Genius
December 24, 2024 - Class variables in Python are a unique and powerful feature that can simplify how data is shared among all instances of a class. Unlike instance variables, which are specific to each object, class variables are shared, making them ideal for ...
🌐
Medium
medium.com › @pouyahallaj › class-vs-instance-variables-in-python-5573e71c99b5
Python Class Variables vs. Instance | Pouya Hallaj | Medium
September 16, 2023 - They differ from instance variables in that they are shared among all instances, providing a convenient way to store constants, track instance counts, and manage shared state. Understanding when and how to use class variables can greatly enhance your Python programming skills and improve code organization.
🌐
W3Resource
w3resource.com › python-interview › what-are-python-class-variables.php
What are Python class variables?
Python class variables are variables that are shared among all instances (objects) of a class.