Python static variable in function
Instead of creating a function having a static local variable, you can always create what is called a "function object" and give it a standard (non-static) member variable. Show
Since you gave an example written C++, I will first explain what a "function object" is in C++. A "function object" is simply any class with an overloaded
In Python, we can also overload Here is a class definition:
Here is an example of the class being used:
The output printed to the console is:
If you want your function to take input arguments, you can add those to
You can make static variables inside a function in many ways in Python. If declaring a static variable in a function means variable throughout the lifetime of the program. Simple 3 example code for it:- Add attributes to a functionYou can add attributes to a function, and use it as a static variable. Count how many times functions have been called using a static variable.
Output: Initialization code at the top using decoratorIf you want the counter initialization code at the top instead of the bottom, you can create a decorator:
Output: Counter is 1 Use hasattr()Alternatively, if you don’t want to set up the variable outside the function, you can use hasattr() to avoid an AttributeError exception:
Output: 1 Do comment if you have any doubts or suggestions on this Python variable topic.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical. How do you define a static variable inside a function in Python?Python doesn't have static variables but you can fake it by defining a callable class object and then using it as a function.
Can we use static variable in function?A static variable in a function is particular to that function. That is, you can only access the variable in that function. Because of this, you could have a static variable in 5 functions, each with the same name. There are simple rules governing static variable that you will need to keep in mind.
How do you keep a variable static in Python?A way to keep the static variables in sync is to make them properties: class Test(object): , _i = 3 , @property , def i(self) , return type(self).
How do I create a static variable and a static function in Python?Create static variables using the constructor and instance method. class Test:. #defining static variable inside constructor.. def __init__(self):. if not hasattr(Test, 'ten'):. Test. ten = 10.. #defining static variable inside class method.. def createTwenty(self):. |