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,730 points
154 views

1 answer to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
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,120 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,710 points
42 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,120 points
44 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,120 points
27 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,730 points
22 views
0 votes
1 answer

how can i count the items in a list?

suppose you have a list a = [0,1,2,3,4,5,6,7,8,9,10] now ...READ MORE

answered May 2 in Python by Mohammad
• 1,400 points
22 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,120 points
46 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,120 points

edited Aug 21, 2018 by Omkar 55 views

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.