A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/g-fact-34-class-or-static-variables-in-python/ below:

Class or Static Variables in Python

Class or Static Variables in Python

Last Updated : 30 Sep, 2024

All objects share class or static variables. An instance or non-static variables are different for different objects (every object has a copy). For example, let a Computer Science Student be represented by a class CSStudent. The class may have a static variable whose value is "cse" for all objects. And class may also have non-static members like name and roll.

 In C++ and Java, we can use static keywords to make a variable a class variable. The variables which don't have a preceding static keyword are instance variables. See this for the Java example and this for the C++ example.

Explanation:
In Python, a static variable is a variable that is shared among all instances of a class, rather than being unique to each instance. It is also sometimes referred to as a class variable because it belongs to the class itself rather than any particular instance of the class.

Static variables are defined inside the class definition, but outside of any method definitions. They are typically initialized with a value, just like an instance variable, but they can be accessed and modified through the class itself, rather than through an instance.

Features of Static Variables

The Python approach is simple; it doesn't require a static keyword. 

Note: All variables which are assigned a value in the class declaration are class variables. And variables that are assigned values inside methods are instance variables.

Example of Static Variables in Python Python
# Python program to show that the variables with a value 
# assigned in class declaration, are class variables

# Class for Computer Science Student
class CSStudent:
    stream = 'cse'                  # Class Variable
    def __init__(self,name,roll):
        self.name = name            # Instance Variable
        self.roll = roll            # Instance Variable

# Objects of CSStudent class
a = CSStudent('Geek', 1)
b = CSStudent('Nerd', 2)

print(a.stream)  # prints "cse"
print(b.stream)  # prints "cse"
print(a.name)    # prints "Geek"
print(b.name)    # prints "Nerd"
print(a.roll)    # prints "1"
print(b.roll)    # prints "2"

# Class variables can be accessed using class
# name also
print(CSStudent.stream) # prints "cse"

# Now if we change the stream for just 'a', it won't be changed for 'b'
a.stream = 'ece'
print(a.stream) # prints 'ece'
print(b.stream) # prints 'cse'

# To change the stream for all instances of the class, we can change it 
# directly from the class
CSStudent.stream = 'mech'

print(a.stream) # prints 'ece'
print(b.stream) # prints 'mech'

Output
cse
cse
Geek
Nerd
1
2
cse
ece
cse
ece
mech

This example shows how class variables (or static variables) are shared across all instances. However, when an instance modifies the class variable, it creates its own copy, which leads to a different behavior.

Key Differences Between Class Variables in Python and Static Variables in Java/C++

While class variables in Python and static variables in Java/C++ serve a similar purpose of being shared across all instances, they behave differently when modified through an instance:

Example to Demonstrate the Difference Python
class MyClass:
    class_var = 'original'  # Class variable

# Creating two instances
obj1 = MyClass()
obj2 = MyClass()

# Changing class_var for obj1 only
obj1.class_var = 'modified'

# Outputs
print(obj1.class_var)  # Output: 'modified'
print(obj2.class_var)  # Output: 'original'
print(MyClass.class_var)  # Output: 'original'

Output
modified
original
original

Explanation: obj1 has created its own version of class_var, separating it from the class-level class_var. As a result, the class variable remains unchanged for other instances.

Instance Variables vs Class Variables in Python Modified Example to Show Behavior Python
class MyClass:
    static_var = 0  # Class variable

    def __init__(self):
        MyClass.static_var += 1  # Modify through class name
        self.instance_var = MyClass.static_var  # Instance variable

obj1 = MyClass()
print("obj1.instance_var:", obj1.instance_var)  # Output: 1

obj2 = MyClass()
print("obj2.instance_var:", obj2.instance_var)  # Output: 2

# Access class variable directly
print("MyClass.static_var:", MyClass.static_var)  # Output: 2

# Modify class variable using obj1 (this creates a new instance variable)
obj1.static_var = 10
print("obj1.static_var:", obj1.static_var)  # Output: 10 (instance variable now)
print("MyClass.static_var:", MyClass.static_var)  # Output: 2 (unchanged)
print("obj2.static_var:", obj2.static_var)  # Output: 2 (unchanged)

Output
obj1.instance_var: 1
obj2.instance_var: 2
MyClass.static_var: 2
obj1.static_var: 10
MyClass.static_var: 2
obj2.static_var: 2
Best Practices for Using Class Variables Advantages: Disadvantages:

Overall, static variables can be a useful tool in Python programming, but they should be used with care and attention to potential downsides, such as inflexibility, hidden dependencies, and thread safety concerns.

Conclusion

Class variables, or static variables, in Python can be a powerful tool when used correctly. They allow you to share data across all instances of a class, but they need to be handled carefully to avoid hidden dependencies or unexpected behavior. Always remember to modify them through the class itself to prevent creating instance-specific variables unintentionally.



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4