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
🌐
GeeksforGeeks
geeksforgeeks.org › python › g-fact-34-class-or-static-variables-in-python
Class (Static) and Instance Variables in Python - GeeksforGeeks
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.
Published: March 6, 2026
Top answer
1 of 16
2410

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
789

@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

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
Static variable in Python? - Stack Overflow
In C++ we have static keyword which in loops is something like this: for(int x=0; x More on stackoverflow.com
🌐 stackoverflow.com
Why wasn't the idea of a Static variable in a function more widely adopted?
If you have a function with a static variable, then that function has one state only. If you write a function that returns a closure, you can have multiple closures, i.e. multiple states. Let's say you write a function like this: int counter() { static int count = 0; return count++; } This means you can call counter and it counts. But there is only one counter. And the call site will always look like this: int current = counter(); Let's switch to Javascript, where you can return a closure: function make_counter() { let counter = 0; return function () { return counter++; }; } Now, the calls look quite different: let counter1 = make_counter(); let counter2 = make_counter(); Now you have two counters, and you can count them independently: let count1 = counter1(); let count2 = counter2(); Does this help? More on reddit.com
🌐 r/C_Programming
38
11
July 26, 2023
private final variables in python?
What use are you trying to achieve with this? python doesn't have truely private , or truly constant variables... More on reddit.com
🌐 r/learnpython
18
1
August 23, 2022
🌐
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, the class containing the cakes may have a variable 'cake' associated with it. This variable is known as a static variable. In Python programming, a static variable is said to be a class variable that is common to all class members.
🌐
Medium
medium.com › @ryan_forrester_ › python-static-variables-complete-guide-f14bed644a6d
Python Static Variables: Complete Guide | by ryan | Medium
October 24, 2024 - They belong to the class itself, not individual objects: class Student: # This is a static variable school_name = "Python High" def __init__(self, name): # This is an instance variable self.name = name # Accessing the static variable through the class print(Student.school_name) # Output: Python High # Creating instances student1 = Student("Alice") student2 = Student("Bob") # Accessing through instances print(student1.school_name) # Output: Python High print(student2.school_name) # Output: Python High
🌐
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.
🌐
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.
Find elsewhere
🌐
Wiingy
wiingy.com › home › learn › python › class or static variable in python
Class or Static Variable in Python
January 30, 2025 - Variables that are defined inside ... a different value for them. The’static’ keyword is used to define static variables, which are shared by all instances of the class....
🌐
Scientech Easy
scientecheasy.com › home › blog › static variable in python
Static Variable in Python - Scientech Easy
August 1, 2026 - In other words, a variable that is mutually shared by all the instances (objects) of a class is called static variable. It is also called class variable or class attribute in Python because it belongs to a class itself rather than any specific ...
🌐
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.
🌐
IncludeHelp
includehelp.com › python › class-or-static-variables.aspx
Class or Static Variables in Python
In Python, class or static variables are shared across all instances of a class, unlike instance variables which are unique to each object.
🌐
TecAdmin
tecadmin.net › what-are-the-python-static-variables
What are the Python Static Variables – TecAdmin
April 26, 2025 - Static variables are variables that are shared among all instances of a class. They are also known as class variables because they are defined at the class level, rather than at the instance level. Static variables are useful when you want to store data that is common to all instances of a class.
🌐
DataFlair
data-flair.training › blogs › how-many-ways-we-can-use-static-variables-in-python
How Many Ways We Can Use Static Variables in Python - DataFlair
February 29, 2024 - Familiarity with the concepts of instance and class variables in Python. ... Basic awareness of memory management in Python and the benefits of optimizing memory usage. # Class Definition class Test: # Static Variable n = 100 # Constructor Method def __init__(self): Test.n += 10 # Non-Static Method def nonstaticmethod(self): Test.n += 10 # Static Method @staticmethod def mystaticmethod(): Test.n += 10 # Class Method @classmethod def myclassmethod(cls): cls.n += 10 # Instances Creation T1 = Test() # Method Calls on Instance T1.nonstaticmethod() # Static Method Call on Class Test.mystaticmethod() # Class Method Call on Instance T1.myclassmethod() # Modifying Static Variable Outside the Class Test.n += 10 # Display the Updated Static Variable print(Test.n)
🌐
Educative
educative.io › answers › how-to-create-and-use-static-class-variables-in-python
How to create and use static class variables in Python
The variables that are defined at the class level are static variables. If we want to create a variable whose value should not be changed, we can use static variables.
🌐
TutorialsPoint
tutorialspoint.com › class-or-static-variables-in-python
Class or Static Variables in Python?
August 28, 2025 - The class variables or static variables are used to share data across all the instances of a class. Unlike instance variables which are specific to each object, class variables maintain a common value for all objects of the class.
🌐
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 - 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. At the beginning, "NewClass.K" has a value of 1. Since "K" is a static variable, then "d.K" will also have the same value (1) - that's how static referencing works.
Top answer
1 of 7
40

Assuming what you want is "a variable that is initialised only once on first function call", there's no such thing in Python syntax. But there are ways to get a similar result:

1 - Use a global. Note that in Python, 'global' really means 'global to the module', not 'global to the process':

_number_of_times = 0

def yourfunc(x, y):
    global _number_of_times
    for i in range(x):
        for j in range(y):
            _number_of_times += 1

2 - Wrap you code in a class and use a class attribute (ie: an attribute that is shared by all instances). :

class Foo(object):
    _number_of_times = 0

    @classmethod
    def yourfunc(cls, x, y):
        for i in range(x):
            for j in range(y):
                cls._number_of_times += 1

Note that I used a classmethod since this code snippet doesn't need anything from an instance

3 - Wrap you code in a class, use an instance attribute and provide a shortcut for the method:

class Foo(object):
    def __init__(self):
         self._number_of_times = 0

    def yourfunc(self, x, y):
        for i in range(x):
            for j in range(y):
                self._number_of_times += 1

yourfunc = Foo().yourfunc

4 - Write a callable class and provide a shortcut:

class Foo(object):
    def __init__(self):
         self._number_of_times = 0

    def __call__(self, x, y):
        for i in range(x):
            for j in range(y):
                self._number_of_times += 1


yourfunc = Foo()

4 bis - use a class attribute and a metaclass

class Callable(type):
    def __call__(self, *args, **kw):
        return self._call(*args, **kw)

class yourfunc(object):
    __metaclass__ = Callable

    _numer_of_times = 0

    @classmethod
    def _call(cls, x, y):
        for i in range(x):
            for j in range(y):                 
                cls._number_of_time += 1

5 - Make a "creative" use of function's default arguments being instantiated only once on module import:

def yourfunc(x, y, _hack=[0]):
    for i in range(x):
        for j in range(y):
            _hack[0] += 1

There are still some other possible solutions / hacks, but I think you get the big picture now.

EDIT: given the op's clarifications, ie "Lets say you have a recursive function with default parameter but if someone actually tries to give one more argument to your function it could be catastrophic", it looks like what the OP really wants is something like:

# private recursive function using a default param the caller shouldn't set
def _walk(tree, callback, level=0):
    callback(tree, level)
    for child in tree.children:
        _walk(child, callback, level+1):

# public wrapper without the default param
def walk(tree, callback):
    _walk(tree, callback)

Which, BTW, prove we really had Yet Another XY Problem...

2 of 7
8

You can create a closure with nonlocal to make them editable (python 3.x only). Here's an example of a recursive function to calculate the length of a list.

def recursive_len(l):
    res = 0
    def inner(l2):
        nonlocal res
        if l2:
            res += 1
            inner(l2[1:])
    inner(l)
    return res

Or, you can assign an attribute to the function itself. Using the trick from here:

def fn(self):
    self.number_of_times += 1
fn.func_defaults = (fn,)
fn.number_of_times = 0

fn()
fn()
fn()
print (fn.number_of_times)
🌐
Medium
medium.com › @emoome82 › static-variables-and-methods-in-python-60505caa16f2
Static Variables and Methods in Python | by civilpy | Medium
July 29, 2024 - In Python, a class serves as a template for creating objects, allowing us to define a set of attributes and methods to represent real-world entities. Within a class, we can define two types of variables and methods: instance variables and static variables/methods.
🌐
Intellipaat
intellipaat.com › home › blog › class or static variables in python
Class or Static Variables in Python - Intellipaat
February 2, 2026 - Static variables in Python are an easy and secure way to share information. A static variable is shared by all objects of a class. It stores common data in one place which helps in avoiding duplicate copies and saves memory.