Class (Static) Variables in Python


Consider the following python class

class Cat(object):

    # class / static variables
    is_mammal = True
    genus = "felis"

    def __init__(self, name="daisy"):
        # instance variables
        self.set_name(name)

    # set / get methods
    def set_name(self, name):
        self.name = str(name)

    def get_name(self):
        return self.name

Class variables can be used without needing to instantiate the class.

print(Cat.is_mammal)
# True

Why Class Variables are Bad

As a general rule, avoid class variables unless they are truly necessary. The reason is simple; they break the most basic principle of Object Oriented Programming, which is that data should be encapsulated. Instances of a class should not have direct access to each other’s data members (instance variables). That would defeat the very purpose of creating separate instances with their own values to begin with.

Example

You can change a class’s static variable like so:

Cat.is_mammal = "yes"
print(Cat.is_mammal)
# yes

However, note that if you do, you will change the value for any existing instances, as well as future instances of the class.

daisy = Cat()
print(daisy.is_mammal)
# True
Cat.is_mammal = "yes"
sophie = Cat()
print(daisy.is_mammal)
# yes
print(sophie.is_mammal)
# yes

Only Use Class Variables For Constants

Class variables exist at the class scope, meaning they are shared by all instances of the class. In this sense, they behave similarly to global variables and should only be used for values that are truly universal (i.e., constants).

In the cat class example, having a reference to the genus of the cat is probably fine as a class variable, since that is constant and should never change. However, you should designate these values as constants by typing them in upper case.

class Cat(object):
    # Constants denoted by upper-case
    IS_MAMMAL = True
    GENUS = "felis"

The fact that class variables are similar to global variables should be enough of a deterrent to use them with extreme caution. Any variable that can be changed or read by many instances at any time creates a fundamentally unpredictable program.