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
๐ŸŒ
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.
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.

People also ask

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ยฎ
Can you modify the value of a class variable from an instance of the class?
Yes, you can modify the value of a class variable from an instance of the class, but doing so will only affect that instance. The value of the class variable will remain the same for all other instances 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 ...
๐ŸŒ
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
๐ŸŒ
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
๐ŸŒ
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.
๐ŸŒ
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.
๐ŸŒ
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.
Find elsewhere
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.

๐ŸŒ
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 ...
๐ŸŒ
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 โ€ฆ
๐ŸŒ
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.
๐ŸŒ
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.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ g-fact-34-class-or-static-variables-in-python
Class (Static) and Instance Variables in Python - GeeksforGeeks
3 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.
๐ŸŒ
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.
๐ŸŒ
Ttu
ttu.github.io โ€บ python-class-instance-variables
Python Class and Instance Variables
July 14, 2022 - In particular, the value-less notation a: int allows one to annotate instance variables that should be initialized in init or new. The proposed syntax is as follows: ... from typing import ClassVar class Starship: captain: str = "Picard" # instance variable with default damage: int # instance variable without default stats: ClassVar[dict[str, int]] = {} # class variable def __init__(self, damage: int, captain: str | None = None): self.damage = damage if captain: self.captain = captain # Else keep the default def hit(self) -> None: Starship.stats['hits'] = Starship.stats.get('hits', 0) + 1 # No
๐ŸŒ
Medium
medium.com โ€บ analytics-vidhya โ€บ are-you-not-sure-where-to-use-class-variables-in-python-cce0af8f514d
Are you not sure where to use class variables in python? | by Kasmitharam | Analytics Vidhya | Medium
February 7, 2024 - And hence it cannot be called via an attribute similar to other instance variables such as pay, first, and last name. The second problem is that if the raise amount(1.04) is mentioned in multiple places, we have to make changes in more than one place which is kind of manually updating stuff. So in order to overcome these scenarios we use class variables.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-classes-and-objects
Python Classes and Objects - GeeksforGeeks
__str__ Implementation: Defined as a method in Dog class. Uses self parameter to access instance's attributes (name and age). Readable Output: When print(dog1) is called, Python automatically uses __str__ method to get a string representation of object. Without __str__, calling print(dog1) would produce something like <__main__.Dog object at 0x00000123>. In Python, variables defined in a class can be either class variables or instance variables and understanding distinction between them is crucial for object-oriented programming.
Published ย  5 days ago
๐ŸŒ
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.