Python equivalent for static variables within a function?

0 votes

What is the idiomatic Python equivalent of this C/C++ code?

void fun()
{
    static int count = 0;
    count++;
    printf("count is %d\n", count);
}

specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?

Oct 17, 2018 in Python by findingbugs
• 4,770 points
710 views

1 answer to this question.

0 votes

You can use the following code, that too will serve the purpose.

def static_vars(**kwargs):
    def decorate(func):
        for k in kwargs:
            setattr(func, k, kwargs[k])
        return func
    return decorate

@static_vars(count=0)
def foo():
    foo.count += 1
    print "Count is %d" % foo.count
answered Oct 17, 2018 by Priyaj
• 56,960 points

Related Questions In Python

0 votes
1 answer

Is there a foreach function in python and is there a way to implement it if there isnt any

Every occurence of "foreach" I've seen (PHP, ...READ MORE

answered Aug 31, 2018 in Python by charlie_brown
• 7,720 points
95 views
0 votes
1 answer

The equivalent of a GOTO in python ​​

Gotos are universally reviled in computer science ...READ MORE

answered Sep 3, 2018 in Python by Priyaj
• 56,960 points
1,684 views
0 votes
1 answer

How can I build a recursive function in python?

I'm wondering whether you meant "recursive". Here ...READ MORE

answered Sep 19, 2018 in Python by Priyaj
• 56,960 points
63 views
0 votes
1 answer

What is equivalent for 'foreach' in Python

Its also interesting to observe this To iterate ...READ MORE

answered Oct 17, 2018 in Python by findingbugs
• 4,770 points
52 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 399 views
+4 votes
6 answers
0 votes
1 answer

What is the Python equivalent for a case/switch statement?

if x == 'a':  # Do the ...READ MORE

answered Jul 26, 2018 in Python by Priyaj
• 56,960 points
111 views
+1 vote
1 answer

What is the function for Factorial in Python

Easiest way: math.factorial(x) (available in 2.6 and ...READ MORE

answered Aug 21, 2018 in Python by Priyaj
• 56,960 points

edited Aug 21, 2018 by Omkar 167 views