Accessing class variables: self.<variable> vs <class name>.<variable>

In exercise 11 there is a code snippet

class SearchEngineEntry:
  secure_prefix = "https://"
  def __init__(self, url):
    self.url = url
  def secure(self):
    return "{prefix}{site}".format(prefix=self.secure_prefix, site=self.url)

secure_prefix is class variable and is referenced with self.secure_prefix syntax.

Is it ok to use SearchEngineEntry.secure_prefix instead? It distinguish the access of class variables from instance variables.

I would say so, since secure_prefix doesn’t get changed each instance (or it shouldn’t). But here is a good article on the matter (far better than any explanation I could conjure up).


This is a good example of “Just because you can, doesn’t mean you should.” It is better to reserve SearchEngineEntry.secure_prefix for only those times when you need to access a variable for the class itself from outside of any instances of the class.

Using self.secure_prefix is more concise and it will reflect any changes to SearchEngineEntry.secure_prefix so long as it isn’t overridden by an instance variable of the same name.

codecademy = SearchEngineEntry("")

# Change class variable
SearchEngineEntry.secure_prefix = "htps://"
print(codecademy.secure_prefix) # prints htps://
print(SearchEngineEntry.secure_prefix) # prints htps://

# Change it back
SearchEngineEntry.secure_prefix = "https://"
print(codecademy.secure_prefix) # prints https://
print(SearchEngineEntry.secure_prefix) # prints https://

If for some reason, you decided to change it for one instance only:

codecademy.secure_prefix = "httppss://"
print(codecademy.secure_prefix) # prints httppss://
print(SearchEngineEntry.secure_prefix) # prints https://

…then a call to self.secure_prefix from the codecademy instance would return the new instance variable instead of the class variable (which is, presumably, what you want if you made that change).