Python Static Variable And Its Methods

Hello geeks and welcome in this article, we will cover Python static variable. Along with that, we will also look at its importance and definition. For an overall better understanding, we will also look at a couple of examples. In general, static means something stationary.

Now with that said, let us try to understand it in general terms. We can understand the Python static variable as a variable present in the class it is defined in. It is also called a class variable because all the objects share it. As we further move ahead in this article, we will look at how it is defined and different ways to access it.

Defining A Python Static Variable

In this section, we will play emphasis on defining the static variable. We will look at the general syntax and other things to pay attention to.

#input
class lang:
    c="low level"
    p="high level"

Above we can see the very basic deceleration using the Static variable. In general, the syntax goes class name: and then followed by the variable declaration. Here we named it as the class as lang and then defined our variables.

Now let us look at a bit more advanced declaration.

class lang:
    def __init__(self,lev,year): 
        self.lev = lev            
        self.year = year           
#objects  
c = lang('low-level', 1972) 
p = lang('high-level', 1991)

Here in the above example, we can see that we have carried on from the first example. But instead of declaring a simple variable, we have used an object for declaring it. Now since we are done with the declaration part now we will try to access the declared variable.

Accessing A Python Static Variable

In this section, our main focus is to access the defined variables. Trust me there are several methods available to us for performing this operation. We will look at each one of them one by one.

1. Direct Method

The direct method allows us to access the variable directly by using the defined class name and the dot operator. It is one of the simplest and the most convenient method to access the static variable. Let’s see this in action.

class lang:
   c="low level"
   p="high level"
print(lang.c)
print(lang.p)

Output:

low level
high level

See how easily we were able to access our value stored using this method.

2. Object Method

In this example, we are going to use the object method to access the stored variable. This method is beneficial when dealing with data on a large scale.

class lang:
   c="low level"
   p="high level"
ob=lang()
print(ob.p)
print(ob.c)

Output:

#output
high level
low level

Here we can see that our output doesn’t change, and we can create an object by just using a single line of code. In the second example that we discussed while talking about declaring the variable also has the object associated with now, let us try to access its elements.

class lang:
    def __init__(self,lev,year): 
        self.lev = lev            
        self.year = year           
#objects  
c = lang('low-level', 1972) 
p = lang('high-level', 1991)

print(c.lev,c.year)
print(p.lev,p.year)

Output:

#output
low-level 1972
high-level 1991

Here above, we can see how we have declared the objects for 2 of our variables and how we accessed them using the object method. These are the methods that we generally use for accessing the object. You can use anyone at your convenience. The one thing you should keep in mind is never trying to access the variable directly. Like this “print(c)” (concerning our example), in that case, you get nothing more than the error.

3. Python Static Variable in a Function

You can declare a static variable by using the function. But you have to add this with a try-except block to initialize the variable on the first call. The following example will help you understand –

Code:

def foo():
    try:
        foo.counter += 1
    except AttributeError:
        foo.counter = 1
    print("Counter is %d" % foo.counter)
foo()
foo()
foo()

Output:

Counter is 1
Counter is 2
Counter is 3

Must Read

Python Null | What is Null in Python | None in Python
Top 10 Algorithms for Data Science
Demystifying Python Attribute Error With Examples
WHAT IS NUMPY DIFF? ALONG WITH EXAMPLES

Conclusion

In this article, we read about Python static Variables. We looked at different methods for defining and accessing the variable through examples. In the end, we can conclude that a variable that is present in the class it is defined in is called Python static variable. I hope this article was able to clear all of your doubts. In case you have any unsolved queries feel free to write them below in the comment section. Done reading this, why not read NumPy Variance next.

Subscribe
Notify of
guest
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Andrii
Andrii
3 years ago

Why do you call class attributes static variables? And you missed the main point, modifying a class variable changes its state for every single instance of that class.