How can I declare a static attribute in Python?
Here is written how I can declare a method: Static methods in Python?
When we declare a variable inside a class but outside any method, it is called as class or static variable in python. Class or static variable can be referred through a class but not directly through an instance.
Static means, that the member is on a class level rather on the instance level. Static variables exist only on class level and aren't instantiated. If you change a static variable in one instance of the class, the change will affect its value in all other instances.
Static variables can be accessed by calling with the class name ClassName. VariableName. When declaring class variables as public static final, then variable names (constants) are all in upper case. If the static variables are not public and final, the naming syntax is the same as instance and local variables.
All variables defined on the class level in Python are considered static
class Example: Variable = 2 # static variable print Example.Variable # prints 2 (static variable) # Access through an instance instance = Example() print instance.Variable # still 2 (ordinary variable) # Change within an instance instance.Variable = 3 #(ordinary variable) print instance.Variable # 3 (ordinary variable) print Example.Variable # 2 (static variable) # Change through Class Example.Variable = 5 #(static variable) print instance.Variable # 3 (ordinary variable) print Example.Variable # 5 (static variable)
You can have two different variables in your class under the same name (one static and one ordinary). Don't be confused.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With