×

Static Variables in Python

What is a Static Variable?

The variable that remains with a constant value throughout the program or throughout the class is known as a " Static Variable ". Static variables are not instantiated, i.e., they are not the created objects but declared variables.

Syntax of Static variables:

class ClassName:
    # static variable is being created immediately after the class declaration
    static_variable = "giving some value to the static variable "
    # the static variable is being accessed and printed
print(ClassName.static_variable)

Static variables are also known as Class variables. A class may contain both Static variables and Non – Static members.

Let us discuss everything about Static variables with an example.

General Example:

Let us consider all humans being represented as a class " Human ". The class " Human " may have a static variable; let it be " x " where x = " Human ". The class may also consist of non – static variables like  “gender“, ” name “, “ place_of_residence “, " mother_tongue ", etc. Here, x is considered to be the common part among all humans, i.e., they are humans.

So, x is a fixed variable within the entire program. Hence, the variable " x " is known as a Static variable, whereas the variables "gender", " name ", " place_of_residence ", and " mother_tongue " differ from person to person. So, they are known as Non – static variables.

In python, we generally do not use the " static " keyword to determine static variables. The variables declared immediately after the class declaration are known to be " Static Variables " or " Class Variables ". The variables declared within the method body are known as " Instance variables ".

Let us see an example program where static variables are declared.

Example program :

#class HumanSpecies is being declared for all humans


class HumanSpecies:
    species = 'Humans'
    def __init__(self,gender,name,place_of_residence,mother_tongue,country):
        self.gender= gender
        self.name= name
        self.place_of_residence= place_of_residence
        self.mother_tongue= mother_tongue
        self.country= country


# creating objects of HumanSpecies class
obj1 = HumanSpecies("Female","Siri","Hyderabad","Telugu","India")
obj2 = HumanSpecies("Male","Kanishk","Mumbai","Hindi","India")


# printing the values using objects
print("The value of Static variable while accessing with object1 is equal to "+obj1.species)
print("The value of Static variable while accessing with object2 is equal to "+obj2.species)
print(obj1.name+" :")
print("My name is "+obj1.name+", and I am from "+obj1.place_of_residence)
print("I can speak "+obj1.mother_tongue+" very fluently.")
print(obj2.name+" :")
print("My name is "+obj2.name+", and I am from "+obj2.place_of_residence)
print("I can speak "+obj2.mother_tongue+" very fluently.")


#printing the value of species using class
print("The value of species before changing is "+HumanSpecies.species)


# as we know that the value of the static variable cannot be changed for all objects, let us try it by changing the value using a single object
obj1.species='Dog'
print("The changed value of static using object1 is "+obj1.species)
print("The value of a static variable while accessing with object2 is "+obj2.species)

The output of the program:

Static variable value while accessing with object1 is equal to Humans
Static variable value while accessing with object2 is equal to Humans
Siri :
My name is Siri, and I am from Hyderabad
I can speak Telugu very fluently.
Kanishk :
My name is Kanishk, and I am from Mumbai
I can speak Hindi very fluently.
The value of species before changing is Humans
The changed value of the static variable using object1 is Dog
The value of the static variable while accessing with object2 is Huma

Explanation:

Initially, the class “ HumanSpecies " is created and declared a static variable, i.e., " species ". The value of the static variable is taken as " Humans ". The non–static members, i.e., “ gender “, ” name “, “ place_of_residence “, “ mother_tongue “, and " country ", have been declared within the function. Two objects are created to access the class "HumanSpecies ”.

Using the objects, the value of the static variable is printed. All the members that have been considered are printed, and then the value of the static variable “ species “ has been modified using the object “ obj1 “. The value has been changed concerning the object " obj1 " but not to " obj2 ". So, when " obj2 " calls the static variable, the initial value " Humans " is printed.

Conclusion:

The value of the static variable cannot be changed unless it is changed using that particular class or an object created within the class.


Related Topics

Scraping data in python

Data scraping is a technique in which one program extracts a set of data from the output of another program. Web scraping is the most common application of this technique....

6 minutes read.

Python EOL (End Of Line)

Introduction An EOL (End Of Line) is defined as a syntax error that indicates that the Python interpreter reached at the end of the line when it tried to scan a...

3 minutes read.

OS Module in Python

What is a module? The Modules are the kind of files that contains python statements and definitions. The module is known by the name of the file followed by the suffix...

8 minutes read.

wxPython Panel class

wxPython Panel class The Widgets which is shown in the frame of GUI window such as text box, buttons, static text etc. are put inside the panel class of the wxpython...

2 minutes read.

Time. Sleep() in Python

Python time sleep () function suspends execution for a certain seconds given by user. Time sleep () syntax: Sleep(seconds) Limitations: The number of seconds to be suspends the code as per its requirements. Returns: Void The execution...

3 minutes read.

BOTTLE Python Web Framework

The Bottle is a lightweight WSGI micro web framework for python. It acts like a thin wrapper around a web server where it is distributed as a single file module...

4 minutes read.

Python String Lowercase

Python Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Python List

The list is one of the most versatile, mutable data-structures in Python. It can store heterogeneous data or different types of data. The list contains comma-separated values (item) within the square brackets. Creating...

4 minutes read.

Python Virtual Environment

In this tutorial, we will understand Virtual Environment in Python. We will understand the need for a virtual environment and also see how to make use of it in python....

3 minutes read.

Python Switch Case

What is a Switch Case Statement? In the programming languages, a switch statement is a logical loop or syntax that tests the variable's value and compares it with multiple cases. Once...

3 minutes read.

Speech Recognition Module in Python

Speech Module in Python: Converting text to speech, known as Speech Synthesis, this process is the computer-generated recreation of human speech. This module converts the human language text into human-like...

8 minutes read.

End Parameter in python

print(): The python print() function prints the program’s output to the output screen. The output can be an integer value, string value or other value. Syntax: print(“hi”) Output: hi will be displayed on the output...

3 minutes read.

Python variance() function

Variance The variance is the average of the square deviations from the mean. The variance will measure the spread of the dataset from its mean or median value. The greater the...

4 minutes read.

Python If-else statement

In real life, there are situations where we have to make decisions for a particular circumstance and based on those decisions, and we plan our next move. The same thing...

4 minutes read.

Imread Python

In this walkthrough, we'll go over the specifics of using the imread() method of OpenCV-Python and various methods for loading images. Imread is an Image reading library. One of the most helpful...

7 minutes read.

Self in Python

 “self" is neither a keyword nor has a special meaning in Python, but it has a place and a job to do in Object-oriented programming. When we create a class...

6 minutes read.

Pltpcolor in Python

Python: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

Python program to check if two strings are anagram or not

Python program to check if two strings are anagram or not Problem: This is a python program that takes two strings and checks if given strings are anagram or not. Examples: Input: string1...

1 minute read.

Difference between Package and Module in Python

What are Python modules? A file with the “.py” suffix that includes Python or C executable code is known as a module. Multiple Python commands and expressions make compose a module....

3 minutes read.

PyShark in Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

4 minutes read.