×

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

Python PPTX

Python-pptx is a python library that enables the user to create and update PowerPoint (.pptx) presentations. It is used to create modified PowerPoint presentations from the db content that can...

10 minutes read.

What is Ipython shell?

IPython is a command shell for computing in multiple programming languages. IPython was developed for python language by Fernando Perez in 2001 as a well-equipped python interpreter that offers shell...

3 minutes read.

Python MySQL

In this article, we are going to learn the following: How to connect Python to MySQL.How to create a new Database.Procedure for connecting the newly created database.Procedure for connecting the already...

7 minutes read.

Word frequency Python

Word frequency Python In this tutorial, we will write the Python program to count the occurrence of a word (word frequency) in a given sentence. We will learn all the approaches...

5 minutes read.

Python K-Means Clustering

K-Means Clustering is a basic yet incredible calculation in information scienceThere are a plenty of true utilizations of K-Means clustering (a couple of which we will cover here)This far reaching...

25 minutes read.

Python String Negative Indexing

This page contains all the information how to use “Negative indexing“ in Python with the help of using slicing. What is an Index? An index is a numeric value, which is assigned...

3 minutes read.

GUI Calculator in Python

Introduction In Python, we can develop a GUI(Graphical User Interface) with multiple options. It offers us some great and commonly used methods for the development of the Graphical User Interface. Tkinter...

4 minutes read.

Python Set update() method

Python Set update() method The set.update() method in Python updates the current set, by adding items from another set. If an element is common in both the sets, only one appearance of this item...

1 minute read.

Hypothesis Testing in Python

Hypothesis Testing in python is widely used along with statistics. Many libraries in Python are very useful for statistics and machine learning. Libraries like numpy, scripy etc. help in hypothesis testing in...

12 minutes read.

Attributes in python

In this article, we shall learn about attributes in python. Classes are a mix of data and functions, which in reality mean attributes and methods respectively. Typically, the body of a...

3 minutes read.

Python all() Function

Python all() Function The all() function in Python returns a Boolean value ‘True’ if all the items in iterable are true or if the iterable object is empty, else it returns False. Syntax all(iterable) Parameter Iterable: An iterable object...

1 minute read.

Tensorflow Angular in Python

TensorFlow is an open-source, Python-compatible toolkit for numerical computation that accelerates and simplifies the creation of neural networks and machine learning algorithms. They make the interesting notion that models can be...

6 minutes read.

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.

EDA in Python

The EDA is the exploratory data analysis; the data scientists mainly use the EDA to understand the main features of the data quickly, the variables in python and the relationship...

6 minutes read.

Data Structures and Algorithms using Python | Part 2

Files: A file is a location or information stored in computer storage devices. File handling is essential when the information or the data is to be held permanently. When we try to...

20 minutes read.

Python Linked List

Linked List Linked lists non-contiguous linear data structure which is made up of nodes and used to store value and a pointer pointing to the next node. It is linked with...

6 minutes read.

Find key from value in dictionary python

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

5 minutes read.

Python for Data Analysis

Data analysis uses various techniques to read, illustrate, manipulate and evaluate a particular data. You can have access to the data and keep the data updated regularly. You can append...

4 minutes read.

Python GUI Programming

GUI (Graphical User Interface) GUI is a graphics-based operating system that uses icons and menus to interact with the user. Python mostly works on CLI (Command Line Interface). Widgets Any user interface has...

4 minutes read.

Decision Tree in Python

Decision Tree is one of the most essential algorithms in the area of machine learning for classification and regression. But let us first talk about the lifespan of every machine learning...

12 minutes read.