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,780 points
4,834 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
• 58,020 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
1,153 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
• 58,020 points
12,700 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
• 58,020 points
1,143 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,780 points
2,465 views
0 votes
2 answers
+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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,434 views
0 votes
1 answer
+5 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,790 points
4,070 views
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
• 58,020 points
959 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
• 58,020 points

edited Aug 21, 2018 by Omkar 1,348 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP