Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a static attribute in Python?

How can I declare a static attribute in Python?

Here is written how I can declare a method: Static methods in Python?

like image 530
Romulus Avatar asked Dec 15 '14 09:12

Romulus


People also ask

How do you declare a static field 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.

What is a static attribute in Python?

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.

How do you declare static variables?

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.


1 Answers

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.

like image 90
Shahriar Avatar answered Sep 20 '22 04:09

Shahriar