Variables declared inside the class definition, but not inside a method are class or static variables:

>>> class MyClass:
...     i = 3
...
>>> MyClass.i
3 

As @millerdev points out, this creates a class-level i variable, but this is distinct from any instance-level i variable, so you could have

>>> m = MyClass()
>>> m.i = 4
>>> MyClass.i, m.i
>>> (3, 4)

This is different from C++ and Java, but not so different from C#, where a static member can't be accessed using a reference to an instance.

See what the Python tutorial has to say on the subject of classes and class objects.

@Steve Johnson has already answered regarding static methods, also documented under "Built-in Functions" in the Python Library Reference.

class C:
    @staticmethod
    def f(arg1, arg2, ...): ...

@beidy recommends classmethods over staticmethod, as the method then receives the class type as the first argument.

Answer from Blair Conrad on Stack Overflow
Top answer
1 of 16
2402

Variables declared inside the class definition, but not inside a method are class or static variables:

>>> class MyClass:
...     i = 3
...
>>> MyClass.i
3 

As @millerdev points out, this creates a class-level i variable, but this is distinct from any instance-level i variable, so you could have

>>> m = MyClass()
>>> m.i = 4
>>> MyClass.i, m.i
>>> (3, 4)

This is different from C++ and Java, but not so different from C#, where a static member can't be accessed using a reference to an instance.

See what the Python tutorial has to say on the subject of classes and class objects.

@Steve Johnson has already answered regarding static methods, also documented under "Built-in Functions" in the Python Library Reference.

class C:
    @staticmethod
    def f(arg1, arg2, ...): ...

@beidy recommends classmethods over staticmethod, as the method then receives the class type as the first argument.

2 of 16
786

@Blair Conrad said static variables declared inside the class definition, but not inside a method are class or "static" variables:

>>> class Test(object):
...     i = 3
...
>>> Test.i
3

There are a few gotcha's here. Carrying on from the example above:

>>> t = Test()
>>> t.i     # "static" variable accessed via instance
3
>>> t.i = 5 # but if we assign to the instance ...
>>> Test.i  # we have not changed the "static" variable
3
>>> t.i     # we have overwritten Test.i on t by creating a new attribute t.i
5
>>> Test.i = 6 # to change the "static" variable we do it by assigning to the class
>>> t.i
5
>>> Test.i
6
>>> u = Test()
>>> u.i
6           # changes to t do not affect new instances of Test

# Namespaces are one honking great idea -- let's do more of those!
>>> Test.__dict__
{'i': 6, ...}
>>> t.__dict__
{'i': 5}
>>> u.__dict__
{}

Notice how the instance variable t.i got out of sync with the "static" class variable when the attribute i was set directly on t. This is because i was re-bound within the t namespace, which is distinct from the Test namespace. If you want to change the value of a "static" variable, you must change it within the scope (or object) where it was originally defined. I put "static" in quotes because Python does not really have static variables in the sense that C++ and Java do.

Although it doesn't say anything specific about static variables or methods, the Python tutorial has some relevant information on classes and class objects.

@Steve Johnson also answered regarding static methods, also documented under "Built-in Functions" in the Python Library Reference.

class Test(object):
    @staticmethod
    def f(arg1, arg2, ...):
        ...

@beid also mentioned classmethod, which is similar to staticmethod. A classmethod's first argument is the class object. Example:

class Test(object):
    i = 3 # class (or static) variable
    @classmethod
    def g(cls, arg):
        # here we can use 'cls' instead of the class name (Test)
        if arg > cls.i:
            cls.i = arg # would be the same as Test.i = arg1

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

Can someone explain how object/instance variables vs class/static variables work in Python?
In the first example, you get an error because the attribute, var1, hasn't been defined before you use it in an expression. So, you would need to do this. class A: def __init__(self): pass def some_func(self): self.var1 += 1 a = A() a.var1 = 0 # create attribute a.some_func() print(a.var1) In your second example, as you've defined a class variable, that is used to define the instance variable the first time you use a local assignment expression in the instance method. Thus, in the below, you will find that a has an instance variable but b doesn't, class A: var1 = 0 def __init__(self): pass def some_func(self): self.var1 += 1 a = A() b = A() a.some_func() print(a.var1, b.var1) print(vars(a), vars(b)) # outputs all the attributes of the instances PS. If I modify the class variable, A.var1 += 10 then you would find b.var1 was also changed (because it is pointing to the same object). More on reddit.com
๐ŸŒ r/learnpython
17
39
July 6, 2023
Confused about class variables, also with inheritance
The class variables and instance variables remain separate if an instance variable of the same name is created. One doesn't override the other, but the class variable will no longer be readable via the object: In [1]: class c: ...: a = 1 ...: def __init__(self): ...: self.a = 2 ...: In [2]: obj = c() In [3]: c.a Out[3]: 1 In [4]: obj.a Out[4]: 2 As for inheritance, yes if you assign a value to a class variable on a child that has the same name as one of the parent's class variables, then a separate class variable of that name will be created for the child. Again, the two will remain separate, one readable from the parent and one readable from the child, but the parent's variable will no longer be visible via the child class. More on reddit.com
๐ŸŒ r/learnpython
10
17
February 24, 2024
Can I have a dataclass variable instantiate the class it is annotated as?
This is a perfect example of why using descriptive names in your code is crucial. @dataclass class Vehicle: wheels: int @dataclass class ParkingSpot: occupant: Vehicle car = Vehicle(4) parking_spot = ParkingSpot(car) print(type(parking_spot.occupant)) If you really want to do this you can use __post_init__ but it starts to get ugly. @dataclass class ParkingSpot(): occupant: Vehicle def __post_init__(self): if not isinstance(self.occupant, Vehicle): self.occupant = Vehicle(self.occupant) parking_spot = ParkingSpot(4) More on reddit.com
๐ŸŒ r/learnpython
11
1
January 2, 2023
AWS Lambda and static variables

If I think I know what you mean, could you use DynamoDB to check what alerts youโ€™ve sent? Or use parameter store to store a static variable the lambda can retrieve.

More on reddit.com
๐ŸŒ r/aws
7
1
March 26, 2017
๐ŸŒ
Wiingy
wiingy.com โ€บ home โ€บ learn โ€บ python โ€บ class or static variable in python
Class or Static Variable in Python
January 30, 2025 - In this example, โ€˜countโ€™ is a static variable of the Student class, and it is shared by all instances of the class. The value of โ€˜countโ€™ is incremented each time a new instance of the class is created. In Python, you must use theโ€™staticโ€™ keyword before the variable name to define a static variable.
๐ŸŒ
Medium
medium.com โ€บ @gauravverma.career โ€บ python-instance-variables-vs-class-variables-static-variables-c8d20f126e3e
Python: Instance Variables vs Class Variables (Static Variables) | by Gaurav Verma | Medium
April 13, 2025 - Just as a villaโ€™s blueprint specifies room dimensions, wall colors, and bathroom layouts, a class defines what an object will contain and how it will behave.
๐ŸŒ
Spark By {Examples}
sparkbyexamples.com โ€บ home โ€บ python โ€บ static or class variables in python?
Static or Class Variables in Python? - Spark By {Examples}
May 31, 2024 - On the other hand, class variables are shared among all instances of the class and are defined outside of any method in the class definition. These class variables are also known as static class variables.
๐ŸŒ
Educative
educative.io โ€บ answers โ€บ how-to-create-and-use-static-class-variables-in-python
How to create and use static class variables in Python
If we want to create a variable whose value should not be changed, we can use static variables. The static variables are accessed by using the class name, such as ClassName.static_variable_name.
๐ŸŒ
Flexiple
flexiple.com โ€บ python โ€บ class-or-static-variables-python
Class Or Static Variables In Python - Flexiple - Flexiple
March 11, 2024 - Class or static variables in Python are shared across all instances of a class, providing a common data attribute accessible to every object created from the class.
Find elsewhere
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ what is a static variable in python?
What is a Static Variable in Python? - Scaler Topics
June 15, 2024 - So, talking about our bakery example, ... variable. In Python programming, a static variable is said to be a class variable that is common to all class members....
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ can someone explain how object/instance variables vs class/static variables work in python?
r/learnpython on Reddit: Can someone explain how object/instance variables vs class/static variables work in Python?
July 6, 2023 -

So I come from a Java background where defining, declaring and accessing static and instance level variables are pretty much a straightforward process. I want to be able to understand OOP concepts of Python properly so I have been doing some practice.

I have a class:

class A:

def init(self): pass

def someFunc(self): self.var1 += 1

I create an object of this class and call the someFunc() method:

a = A() 
a.someFunc()

It gives me an error. Ok, fair enough since I haven't declared a self.var1 variable yet.

Consider another example.

class A:

var1 = 10

def init(self): pass

def someFunc(self): self.var1 += 1

Now when I do this:

a = A()
a.someFunc()

Output: 11

I know that variables defined just below the class definition are class/static variables. And to access them you have to do A.var1

But why does it not give me an error now? I haven't created a object/instance level self.var1 variable yet, just a class level variable var1.

And when I call A.var1 the output is 10. Why is the output not the same as a.var1?

Does python automatically use the class level variable with the same name since there is no instance level variable defined with the same name? And does that in turn become a different variable from the class level variable?

Can someone please elaborate?

Top answer
1 of 11
9
In the first example, you get an error because the attribute, var1, hasn't been defined before you use it in an expression. So, you would need to do this. class A: def __init__(self): pass def some_func(self): self.var1 += 1 a = A() a.var1 = 0 # create attribute a.some_func() print(a.var1) In your second example, as you've defined a class variable, that is used to define the instance variable the first time you use a local assignment expression in the instance method. Thus, in the below, you will find that a has an instance variable but b doesn't, class A: var1 = 0 def __init__(self): pass def some_func(self): self.var1 += 1 a = A() b = A() a.some_func() print(a.var1, b.var1) print(vars(a), vars(b)) # outputs all the attributes of the instances PS. If I modify the class variable, A.var1 += 10 then you would find b.var1 was also changed (because it is pointing to the same object).
2 of 11
5
In python classes a reference to self.varname first looks for an instance attribute varname. If found, it is used. But if not found the class variable varname is used, if it exists. When assigning to self.varname an instance attribute is always created or updated, leaving any class variable of the same name unchanged. You can see that in this code, based on your second example: class A: var1 = 10 # no need to use "pass" in __init__() def someFunc(self): self.var1 += 1 a = A() a.someFunc() print(f"{a.var1=}, {A.var1=}") Run that code and you will see the instance variable is 11 and the class variable remains unchanged at 10. It's good practice to always refer to class variables by A.var1 so you don't fall into the trap of thinking assigning to self.var1 changes the class variable of name var1.
๐ŸŒ
Medium
medium.com โ€บ @ryan_forrester_ โ€บ python-static-variables-complete-guide-f14bed644a6d
Python Static Variables: Complete Guide | by ryan | Medium
October 24, 2024 - Hereโ€™s how to handle both types of variables clearly: class Employee: company_name = "Tech Corp" # Static variable employee_count = 0 # Static variable def __init__(self, name, salary): self.name = name # Instance variable self._salary = salary # Instance variable Employee.employee_count += 1 @classmethod def set_company_name(cls, name): cls.company_name = name @property def salary(self): return self._salary @salary.setter def salary(self, value): if value < 0: raise ValueError("Salary cannot be negative") self._salary = value # Usage emp1 = Employee("Alice", 50000) emp2 = Employee("Bob", 60000) print(Employee.employee_count) # Output: 2 Employee.set_company_name("New Tech Corp") print(emp1.company_name) # Output: New Tech Corp
๐ŸŒ
FavTutor
favtutor.com โ€บ blogs โ€บ static-variable-python
Static Variable in Python (How to Create and Access it?)
September 12, 2022 - Python does not have a 'static' keyword to declare the static variable. In Python, you simply declare a variable inside the class, note that it should not be inside any method, and that variable will be known as a static or class variable.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ class-or-static-variables-in-python
Class or Static Variables in Python?
In this article we are going to learn about class or static variables on python. The class variables or static variables that are used to share across all the instances of a class. Unlike the instance variables which are specific to each object, Clas
๐ŸŒ
Radek
radek.io โ€บ posts โ€บ static-variables-and-methods-in-python
Static variables and methods in Python
July 21, 2011 - All variables defined on the class level in Python are considered static.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ g-fact-34-class-or-static-variables-in-python
Class or Static Variables in Python - GeeksforGeeks
September 30, 2024 - See this for the Java example and this for the C++ example. Explanation: In Python, a static variable is a variable that is shared among all instances of a class, rather than being unique to each instance.
๐ŸŒ
Sololearn
sololearn.com โ€บ en โ€บ Discuss โ€บ 3095686 โ€บ static-variable-in-python-class
Static variable in Python class | Sololearn: Learn to code for FREE!
October 19, 2022 - "K" is a static variable of the class "NewClass". Static variables can be accessed and modified without the need for an instance of the class. When you instantiate "NewClass", any static attributes are also "saved" to the new object.
๐ŸŒ
Real Python
realpython.com โ€บ instance-class-and-static-methods-demystified
Python's Instance, Class, and Static Methods Demystified โ€“ Real Python
March 17, 2025 - These are the most common methods in Python classes. Class methods use a cls parameter pointing to the class itself. They can modify class-level state through cls, but they canโ€™t modify individual instance state. Static methods donโ€™t take self or cls parameters.
๐ŸŒ
Dive into Python
diveintopython.org โ€บ home โ€บ learn python programming โ€บ classes in python โ€บ static class and methods
Static Classes in Python - How to Call Static Methods, Use Static Variables
May 3, 2024 - The TextUtils class contains a ... string in uppercase. In Python, static variables are class-level variables that are shared among all instances of the class....
๐ŸŒ
Javatpoint
javatpoint.com โ€บ static-in-python
Static in Python - Javatpoint
Static in Python with python, tutorial, tkinter, button, overview, entry, checkbutton, canvas, frame, environment set-up, first python program, operators, etc.
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ python โ€บ static class variable in python
Static Class Variables in Python | Delft Stack
March 11, 2025 - In Python, a static class variable is defined within a class but outside any instance methods. This means that it is not tied to a specific instance of the class, allowing all instances to access the same variable.
๐ŸŒ
Studytonight
studytonight.com โ€บ python โ€บ python-static-keyword
Python Static Variables and Methods | Studytonight
In Python, there is no special keyword for creating static variables and methods. Python follows a different but simple approach for defining static variables and methods which we will learn in this tutorial. Class or Static variables are the variables that belong to the class and not to objects.