Python Class Variables

Created with Sketch.

Python Class Variables

Summary: in this tutorial, you’ll learn how the Python class variables (or attributes) work.

Introduction to the Python class variables

Everything in Python is an object including a class. In other words, a class is an object in Python.

When you define a class using the class keyword, Python creates an object with the name the same as the class’s name. For example:

class HtmlDocument:
pass

Code language: Python (python)

This example defines the HtmlDocument class and the HtmlDocument object. The HtmlDocument object has the __name__ property:

print(HtmlDocument.__name__) # HtmlDocument

Code language: Python (python)

And the HTMLDocument has the type of type:

print(type(HtmlDocument)) # <class 'type'>

Code language: Python (python)

It’s also an instance of the type class:

print(isinstance(HtmlDocument, type)) # True

Code language: Python (python)

Class variables are bound to the class. They’re shared by all instances of that class.

The following example adds the extension and version class variables to the HtmlDocument class:

class HtmlDocument:
extension = 'html'
version = '5'

Code language: Python (python)

Both extension and version are the class variables of the HtmlDocument class. They’re bound to the HtmlDocument class.

Get the values of class variables

To get the values of class variables, you use the dot notation (.). For example:

print(HtmlDocument.extension) # html
print(HtmlDocument.version) # 5

Code language: Python (python)

If you access a class variable that doesn’t exist, you’ll get an AttributeError exception. For example:

HtmlDocument.media_type

Code language: Python (python)

Error:

AttributeError: type object 'HtmlDocument' has no attribute 'media_type'

Code language: Python (python)

Another way to get the value of a class variable is to use the getattr() function. The getattr() function accepts an object and a variable name. It returns the value of the class variable. For example:

extension = getattr(HtmlDocument, 'extension')
version = getattr(HtmlDocument, 'version')
print(extension) # html
print(version) # 5

Code language: Python (python)

If the class variable doesn’t exist, you’ll also get an AttributeError exception. To avoid the exception, you can specify a default value if the class variable doesn’t exist like this:

media_type = getattr(HtmlDocument, 'media_type', 'text/html')
print(media_type) # text/html

Code language: Python (python)

Set values for class variables

To set a value for a class variable, you use the dot notation:

HtmlDocument.version = 10

Code language: Python (python)

or you can use the setattr() built-in function:

setattr(HtmlDocument, 'version', 10)

Code language: Python (python)

Since Python is a dynamic language, you can add a class variable to a class at runtime after you have created it. For example, the following adds the media_type class variable to the HtmlDocument class:

HtmlDocument.media_type = 'text/html'
print(HtmlDocument.media_type)

Code language: Python (python)

Similarly, you can use the setattr() function:

setattr(HtmlDocument, media_type, 'text/html')
print(HtmlDocument.media_type)

Code language: Python (python)

Delete class variables

To delete a class variable at runtime, you use the delattr() function:

delattr(HtmlDocument, 'version')

Code language: Python (python)

Or you can use the del keyword:

del HtmlDocument.version

Code language: Python (python)

Class variable storage

Python stores class variables in the __dict__ attribute. The __dict__ is a mapping proxy, which is a dictionary. For example:

from pprint import pprint

class HtmlDocument:
extension = ‘html’
version = ‘5’

HtmlDocument.media_type = ‘text/html’

pprint(HtmlDocument.__dict__)

Code language: Python (python)

Output:

mappingproxy({'__dict__': <attribute '__dict__' of 'HtmlDocument' objects>,
'__doc__': None,
'__module__': '__main__',
'__weakref__': <attribute '__weakref__' of 'HtmlDocument' objects>,
'extension': 'html',
'media_type': 'text/html',
'version': '5'})

Code language: Python (python)

As clearly shown in the output, the __dict__ has three class variables: extension, media_type, and version besides other predefined class variables.

Python does not allow you to change the __dict__ directly. For example, the following will result in an error:

HtmlDocument.__dict__['released'] = 2008

Code language: Python (python)

Output:

TypeError: 'mappingproxy' object does not support item assignment

Code language: Python (python)

However, you can use the setattr() function or dot notation to indirectly change the __dict__ attribute.

Also, the key of the __dict__ are strings that will help Python speeds up the variable lookup.

Although Python allows you to access class variables through the __dict__ dictionary, it’s not a good practice. Also, it won’t work in some situations. For example:

print(HtmlDocument.__dict__['type']) # BAD CODE

Code language: Python (python)

Callable class attributes

Class attributes can be any object such as a function.

When you add a function to a class, the function becomes a class attribute. Since a function is callable, the class attribute is called a callable class attribute. For example:

from pprint import pprint

class HtmlDocument:
extension = ‘html’
version = ‘5’

def render():
print(‘Rendering the Html doc…’)

pprint(HtmlDocument.__dict__)

Code language: Python (python)

Output:

mappingproxy({'__dict__': <attribute '__dict__' of 'HtmlDocument' objects>,
'__doc__': None,
'__module__': '__main__',
'__weakref__': <attribute '__weakref__' of 'HtmlDocument' objects>,
'extension': 'html',
'render': <function HtmlDocument.render at 0x0000010710030310>,
'version': '5'})
Rendering the Html doc...

Code language: Python (python)

In this example, the render is a class attribute of the HtmlDocument class. Its value is a function.

Summary

  • A class is an object which is an instance of the type class.
  • Class variables are attributes of the class object.
  • Use dot notation or getattr() function to get the value of a class attribute.
  • Use dot notation or setattr() function to set the value of class attribute.
  • Python is a dynamic language. Therefore, you can assign a class variable to a class at runtime.
  • Python stores class variables in the __dict__ attribute. The __dict__ attribute is a dictionary.

Leave a Reply

Your email address will not be published. Required fields are marked *