Python Program on Static Variable

Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python

Static variables in Python provide a mechanism for sharing data among instances of a class while remaining associated with the class itself. Unlike instance variables, which are unique to each instance, static variables maintain a single value for the entire class.

This concept introduces a level of data persistence that is shared across instances, offering a practical way to store information common to all objects of a class. In this article, we will explore the intricacies of static variables in Python, demonstrating their usage through practical examples and highlighting their impact on class-level data management.

Topic Explanation:

Static variables in Python introduce a distinctive layer of functionality within the object-oriented paradigm, enabling the sharing of data across instances while preserving a singular value for the entire class. This aspect of Python programming facilitates an elegant means of managing class-level data efficiently. By diverging from the instance-specific nature of variables, static variables offer a centralized approach, allowing developers to streamline the handling of information that remains consistent throughout all instances. This nuanced capability not only promotes a more systematic organization of shared data but also simplifies the process of manipulating and updating values that are universally applicable within the class.

Within the landscape of Python’s object-oriented principles, static variables play a pivotal role in fostering a cohesive environment for class-wide information. Their unifying nature extends beyond mere data storage, serving as a dynamic conduit for maintaining consistency and coherence across multiple instances. The exploration of static variables in this context unravels their utility in creating structured, adaptable, and maintainable code. By grasping the intricacies of static variables, developers can wield this feature to enhance the robustness of their codebases, leading to more intuitive class designs and promoting a harmonious sharing of data among instances.

Prerequisites:

Basic Understanding of Classes and Objects:

  • Knowledge of how to define classes and create instances in Python.

Instance and Class Variables:

  • Familiarity with the concepts of instance and class variables.

Basic Python Syntax:

  • Proficiency in basic Python syntax, including variable assignments and method definitions.

Code 1 with Comments:

# Class Definition
class Myclass:
    n = 10  # Static variable
    # Method to Increment Static Variable
    def incr(self):
        Myclass.n += 10
    # Method to Display Static Variable
    def display(self):
        print(Myclass.n)
# Instances Creation
M1 = Myclass()
M2 = Myclass()
# Instance Method Calls
M1.incr()
M1.incr()
M2.display()

Output:
30

Code 1 with Explanation:

Class Definition:

  • class Myclass: declares a class named Myclass.

Static Variable:

  • n = 10 initializes a static variable n with an initial value of 10.

Increment Method:

  • def incr(self): defines a method incr that increments the static variable n by 10.

Display Method:

  • def display(self): defines a method display that prints the current value of the static variable n.

Instances Creation:

  • M1 = Myclass() creates an instance of Myclass named M1.
  • M2 = Myclass() creates another instance of Myclass named M2.

Instance Method Calls:

  • M1.incr(), M1.incr() calls the incr method on the M1 instance twice, incrementing the static variable.
  • M2.display() calls the display method on the M2 instance, displaying the current value of the static variable.

Code 2 with Comments:

# Class Definition
class Student:
    # Static Variables
    clgName = "Data Flair Indore"
    stname = "MP"
    country = "India"
    # Constructor Method
    def __init__(self, rno, name):
        # Instance Variables
        self.rno = rno
       self.name = name
    # Display Method
    def display(self):
        print(self.rno)
        print(self.name)
        print(Student.clgName)
        print(Student.stname)
        print(Student.country)
# Instances Creation with Constructor Arguments
S1 = Student(101, "Vivek")
S2 = Student(102, "Ashok")
# Method Calls on Instances
S1.display()
S2.display()

Output:
101
Vivek
Data Flair Indore
MP
India
102
Ashok
Data Flair Indore
MP
India

Code 2 With Explanation:

Class Definition:

  • class Student: declares a class named Student.

Static Variables:

  • clgName, stname, and country are static variables holding information about the college, state, and country.

Constructor Method:

  • def __init__(self, rno, name): is a constructor method that initializes instance variables rno and name.

Instance Variables:

  • self.rno = rno assigns the value of rno to the instance variable.
  • self.name = name assigns the value of name to the instance variable.

Display Method:

  • def display(self): defines a method display to print instance and static variables.

Instances Creation with Constructor Arguments:

  • S1 = Student(101, “Vivek”) creates an instance of Student with specific values.
  • S2 = Student(102, “Ashok”) creates another instance of Student with different values.

Method Calls on Instances:

  • S1.display() calls the display method on the S1 instance, printing the information.
  • S2.display() calls the display method on the S2 instance, printing different information.

Conclusion:

In conclusion, the practical exploration of static variables in Python highlights their significance in sharing data among class instances. The examples illustrate how static variables provide a means to store and manipulate information common to all objects of a class, contributing to more efficient class-level data management. Understanding the role of static variables enhances a developer’s ability to design classes that effectively utilize shared information, promoting code clarity and maintainability. The presented programs showcase the practical application of static variables in both incrementing values across instances and storing shared details among class objects. This foundational knowledge of static variables is instrumental for developers aiming to create robust and well-structured Python programs.

If you are Happy with DataFlair, do not forget to make us happy with your positive feedback on Google

courses

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

Your email address will not be published. Required fields are marked *