
Matthew P. answered 10/09/19
Software Engineer with BSE degree in Computer Science
Yes! Static variables are possible in Python, as are static methods. The Python nomenclature is somewhat different from other languages such as Java and C++, and is not entirely internally consistent.
- In Python, a static variable is the same as a class variable. These are variables that are stored in the class, not in an instance of the class, and cannot be changed.
- In Python, a static method (function) is not the same as a class method (function).
- A static method cannot access or modify any information from the class or any instance of the class; it takes in arguments, processes them as the code specifies, and returns a value.
- A class method can access the state of the class and modify information in the class, which would affect all instances of the class.
Let's say we have a class representing a Person.
- All Persons are of the same species, which is the same for all Persons and can't change, so we want to represent that information as a static (class) variable.
- Persons also have a name and an age, which are different for each Person and can change, so we represent those as instance variables.
- Persons should be able to tell you their name and age, so we have instance methods to return these values.
- Let's also say we want the Person to be able to do simple math regardless of any of his attributes; specifically, he should be able to add two numbers. We will do this with a static method.
- Finally, let's say we want the Person to be able to "hear" (receive as an argument) a species name and tell us whether he is of that species. For this we would need a class method, since we are taking in an argument and comparing it to a class variable. We will represent the output as a Boolean value.
Here is what the code would look like: