Python Static Variables & Static Functions
Python Static Variables & Static Functions Interview Questions
What are static variables in Python?
Static variables (class variables) are variables that are shared by all instances of a class. They are defined within the class but outside any methods. Example: class MyClass: count = 0 - 'count' is a static variable shared by all instances.
What is the difference between instance variables and static variables?
Instance variables are unique to each object instance, while static variables are shared by all instances. Instance variables are defined inside methods (usually __init__), while static variables are defined at class level. Changes to static variables affect all instances.
What are static methods in Python?
Static methods are methods that belong to a class rather than an instance. They don't have access to self or cls parameters. Defined using @staticmethod decorator. They are utility functions that don't modify class or instance state.
How to define a static method?
Use the @staticmethod decorator. Example: class MathUtils: @staticmethod def add(x, y): return x + y. Call using class name: MathUtils.add(5, 3) or instance: obj.add(5, 3).
What is the difference between @staticmethod and @classmethod?
@staticmethod doesn't receive any implicit first argument. @classmethod receives cls as first argument. Static methods are utility functions, while class methods can access and modify class state.
How to access static variables?
Static variables can be accessed using: 1. Class name: ClassName.variable. 2. Instance: instance.variable (Python searches instance namespace first, then class namespace). It's recommended to use class name for clarity.
When to use static methods?
Use static methods when: 1. The method doesn't need access to instance or class state. 2. It's a utility function logically related to the class. 3. You want to group related functions under a class namespace. 4. For factory methods that don't need class state.
Can static methods be overridden?
Yes, static methods can be overridden in subclasses, but unlike instance methods, they don't follow polymorphism in the same way. When called from a subclass, Python will use the static method defined in that subclass or its parent class.
What happens if you modify a static variable through an instance?
If you do instance.variable = value, Python creates an instance variable with the same name, shadowing the class variable. The class variable remains unchanged for other instances. Use ClassName.variable = value to modify the class variable.
How to create a counter using static variables?
Use a static variable to track count across all instances: class Counter: count = 0; def __init__(self): Counter.count += 1. Each new instance increments the shared count. Access with Counter.count.
What are class constants and how to define them?
Class constants are static variables with values that shouldn't change. Conventionally written in UPPERCASE. Example: class Math: PI = 3.14159; MAX_VALUE = 100. These are accessed as Math.PI and should not be modified.
Can static methods access instance variables?
No, static methods cannot access instance variables directly because they don't receive self parameter. They can only work with the arguments passed to them. If you need to access instance state, use an instance method instead.
How do static variables work with inheritance?
Static variables are inherited by subclasses. If a subclass modifies a static variable, it affects that class and its instances, but not the parent class. Each class has its own namespace for static variables, but they can be accessed through inheritance chain.
What is the memory allocation for static variables?
Static variables are allocated once when the class is defined (when the module is loaded). They exist in the class's namespace, not in each instance. This makes them memory efficient when shared data is needed across many instances.
How to list all static variables of a class?
Use vars(ClassName) or ClassName.__dict__ to see class namespace. Filter for non-callable attributes: [attr for attr in dir(ClassName) if not callable(getattr(ClassName, attr)) and not attr.startswith('__')].
Can you have private static variables?
Yes, using name mangling with double underscores: __private_static. However, true privacy doesn't exist in Python. It's a convention. Single underscore _protected_static indicates "protected" (shouldn't be accessed outside class/subclasses).
What are the performance benefits of static methods?
Static methods are slightly faster than instance methods because they don't need to create or pass self parameter. They also use less memory as they're bound to the class, not instances. However, the performance difference is usually negligible.
How to use static variables for configuration settings?
Use static variables to store configuration: class Config: DATABASE_URL = "localhost"; DEBUG = True; TIMEOUT = 30. Access anywhere: Config.DATABASE_URL. Can be overridden in subclasses for different environments.
What is the difference between module-level functions and static methods?
Module-level functions exist in module namespace, static methods exist in class namespace. Static methods provide better organization when the function is logically related to a class. Static methods can be overridden in subclasses, module functions cannot.
Best practices for using static variables and methods?
1. Use for data/methods shared by all instances. 2. Use UPPERCASE for constants. 3. Access static variables via class name, not instances. 4. Use static methods for pure functions. 5. Document their purpose clearly. 6. Avoid mutable static variables when thread safety is needed.
Note: Static variables and methods are fundamental to object-oriented programming in Python. They provide a way to share data and functionality across all instances of a class, offering memory efficiency and organizational benefits. Understanding when to use static vs instance members is crucial for writing clean, efficient, and maintainable Python code.