What is the Python equivalent of static variables inside a function?

637    Asked by manishJhadav in Python , Asked on Apr 5, 2021

 I have this example in C/C++ and I want the same code for Python

void numbers()
{
    static int count = 0;
    count++;
    printf("count is %dn", count);
}

How to implement static member at a function level as opposed to the class level?If I place a function into a class will it change anything?

Answered by manish Jhadav

To get a python static variable in function you can add attributes to a function, and use it as a static variable.

def function():
  function.counter += 1
  print(function.counter)
function.counter = 0

Your Answer

Interviews

Parent Categories