#FutureSTEMLeaders - Wiingy's $2400 scholarship for School and College Students

Apply Now

Python

Class or Static Variable in Python

Written by Rahul Lath

Python Tutorials

1Python Overview2Python Tutorial: A Comprehensive Guide for Beginners3Python Keywords and Identifiers4Download and Installation Guide for Python5Python Syntax (With Examples)6Python Comments7Python Variables (With Examples)8Taking Input in Python9Output in Python10File Handling in Python (Files I/O)11Python Operators (With Examples)12Ternary Operators in Python13Operator Overloading in Python14Division Operators in Python15Input from Console in Python16Output Formatting in Python17Any All in Python18Difference between Python Equality and Identity Operators19Python Membership and Identity Operators20Python Data Types21Python Dictionary22Control Flow in Python23Python Arrays24Looping Techniques in Python25Chaining Comparison Operators in Python26Python Functions27Python Strings28Python Numbers29Python Sets30Python For Loops31Python While Loops32Python Break Statement:33Python Continue Statement34Python pass Statement35Args and Kwargs in Python36Python Generators37Python Lambda38Global and Local Variables in Python39Global Keyword in Python40Python Closures41Python Decorators42Memoization using Decorators in Python43Constructors in Python44Encapsulation in Python45Inheritance in Python46Polymorphism in Python47Class Method vs Static Method in Python48Python Exception Handling49First Class Functions in Python50Python Classes And Objects51Errors and Exceptions in Python52Built-In Exceptions in Python53Append to file in Python54File Handling in Python55Destructors in Python56User-Defined Exceptions in Python57Class or Static Variable in Python58Python Tuples59Reading File in Python60Writing File in Python61Opening and Closing Files in Python62NZEC error in Python63Operator Function64Webscraper Python Beautifulsoup65Python Pyramid Patterns66Python Start Patterns67Web Crawler in Python68Build a Python Youtube Downloader69Currency Convertor in Python70Python Website Blocker
tutor Pic

What is a Static Variable in Python?

Static variables in Python are global variables used by every instance of a class. In contrast to instance variables, static variables are part of the class itself and are not associated with any particular. This indicates that the static variable’s value is shared by every instance of a class.

When a class is defined, the static keyword is used to define variables, which are initialized just once. They remain valuable for the duration of the program, and any modifications have an impact on every instance of the class.

An in-depth explanation of static variables in Python, including their definition, usage, and examples, is the aim of this article.

Instance Variables vs. Static Variables in Python

Variables that are defined inside a class and are unique to each object or instance of the class are known as instance variables. They are created when an object is instantiated and each instance of the class may have a different value for them.

The’static’ keyword is used to define static variables, which are shared by all instances of the class. They are made when a class is defined, and they continue to be valuable for the duration of the program.

To summarize, the key differences between instance variables and static variables are:

Static variables are shared by all instances of the class, whereas instance variables are unique to each object or instance of the class.

Static variables are created when a class is defined, whereas instance variables are created when an object is instantiated.

In Python, instance variables include the following examples:

class Car: def __init__(self, make, model): self.make = make self.model = model car1 = Car("Toyota", "Camry") car2 = Car("Honda", "Accord") print(car1.make) # Output: Toyota print(car2.make) # Output: Honda

In this example, ‘make’ and ‘model’ are instance variables of the Car class, and they have different values for each instance of the class.

Examples of static variables in Python include:

class Student: count = 0 # static variable def __init__(self, name): self.name = name Student.count += 1 # increment count on each instance creation student1 = Student("John") student2 = Student("Mary") print(Student.count) # Output: 2

In this example, ‘count’ is a static variable of the Student class, and it is shared by all instances of the class. The value of ‘count’ is incremented each time a new instance of the class is created.

How to Define Static Variables in Python

In Python, you must use the’static’ keyword before the variable name to define a static variable. Here’s the syntax:

class MyClass: static_var = value

Where ‘MyClass’ is the name of the class, ‘static_var’ is the name of the static variable, and ‘value’ is the initial value of the static variable.

Anywhere in the class definition, including inside methods, class methods, and static methods, is a place where static variables can be defined.

Here are some examples of defining static variables in Python:

class Circle: pi = 3.14 # static variable def __init__(self, radius): self.radius = radius def area(self): return Circle.pi * self.radius ** 2 circle1 = Circle(5) print(circle1.area()) # Output: 78.5

In this example, ‘pi’ is a static variable of the Circle class, and it is used inside the ‘area’ method to calculate the area of a circle.

Here’s another example of defining static variables inside a class method:

class Employee: num_employees = 0 # static variable def __init__(self, name, salary): self.name = name self.salary = salary Employee.num_employees += 1 @classmethod def get_num_employees(cls): return cls.num_employees employee1 = Employee("John Doe", 50000) employee2 = Employee("Jane Smith", 60000) print(Employee.get_num_employees()) # Output: 2

In this example, ‘num_employees’ is a static variable of the Employee class, and it is incremented each time a new instance of the class is created inside the ‘init’ method. The ‘get_num_employees’ class method is used to access the value of the static variable.

In conclusion, static variables are an important concept in Python programming, and understanding their usage and definition can be useful in writing efficient and effective code.

Accessing Static Variables in Python

In Python, you can use the class name or the instance name, the dot (.) operator, and the name of the static variable to access a static variable. Here’s the syntax:

ClassName.static_var instance_name.static_var

When accessing a static variable, you don’t need to create an instance of the class. The value of the static variable is the same for all instances of the class.

The key differences between accessing static variables and instance variables are:

Accessing static variables uses the class name or instance name followed by the dot (.) operator, while accessing instance variables uses only the instance name followed by the dot (.) operator.

Static variables can be accessed without creating an instance of the class, while instance variables can only be accessed through an instance of the class.

Here are some examples of accessing static variables in Python:

class BankAccount: interest_rate = 0.05 # static variable account1 = BankAccount() account2 = BankAccount() print(BankAccount.interest_rate) # Output: 0.05 print(account1.interest_rate) # Output: 0.05 print(account2.interest_rate) # Output: 0.05

In this example, ‘interest_rate’ is a static variable of the BankAccount class, and it is accessed using both the class name and instance names.

When to Use Static Variables in Python

Static variables can be useful in various programming scenarios, such as:

  • When you need to maintain a value that is common to all instances of a class.
  • When you want to avoid redundant computation or data storage.
  • When you need to keep track of certain statistics or counters.

The benefits of using static variables include:

Effective memory usage: Static variables can save memory because they are shared by all instances of the class and only need to be stored once.

Simpler code maintenance: Static variables make it simple to keep track of frequent values or statistics, which can make it easier to maintain and debug code.

Here are some examples of when to use static variables:

class Logger: log_file = "app.log" # static variable @staticmethod def log(message): with open(Logger.log_file, "a") as f: f.write(message + "\n") Logger.log("Application started.")

In this example, ‘log_file’ is a static variable of the Logger class, and it is used inside the ‘log’ static method to write messages to a log file. By using a static variable, the log file name is common to all instances of the class, and it can be easily changed if needed.

class Counter: count = 0 # static variable def __init__(self): Counter.count += 1 @staticmethod def get_count(): return Counter.count counter1 = Counter() counter2 = Counter() print(Counter.get_count()) # Output: 2

In this example, ‘count’ is a static variable of the Counter class, and it is used inside the ‘init’ method to count the number of instances of the class. By using a static variable, the counter is common to all instances of the class, and it can be easily accessed using the ‘get_count’ static method.

Conclusion

Static variables are a crucial part of Python programming that facilitate effective memory management and simpler code maintenance. Understanding static variables will help you write better code and approach problems in programming more successfully. If you want to avoid duplicating computation or data storage, maintain a value that is common to all instances of a class, or keep track of specific statistics or counters, keep in mind to use static variables.

You can define a static variable by using the ‘static’ keyword before the variable name, and you can access a static variable by using the class name or instance name followed by the dot (.) operator.

You can make difficult programming tasks simpler and increase program performance by using static variables in your code. It is crucial to remember that static variables should only be used sparingly and when absolutely necessary. After reading this article, you ought to have a firm grasp on static variables in Python and know how to use them efficiently in your programs.

FAQs

Can you make static variables in Python?

In Python, you can create static variables by adding the keyword “static” before the variable name.

What is static variable with example?

A class-level Python variable that is shared by every instance of the class is known as a static variable. Here’s an illustration:
class Car:
    num_wheels = 4  # static variable
car1 = Car()
car2 = Car()
print(car1.num_wheels)  # Output: 4
print(car2.num_wheels)  # Output: 4
In this example, 'num_wheels' is a static variable of the Car class, and it is shared by all instances of the class.

What purpose does static serve in Python?

In Python, class-level variables and methods that are shared by all instances of the class are defined using the “static” keyword.

What is a static variable?

In Python, a static variable is one that is shared by every instance of the class.

Written by

Rahul Lath

Reviewed by

Arpit Rankwar

Share article on

tutor Pic
tutor Pic