- Python Class Variables
- Introduction to the Python class variables
- Get the values of class variables
- Set values for class variables
- Delete class variables
- Class variable storage
- Callable class attributes
- Summary
- Python access to class variables
- # Table of Contents
- # Updating class variables in Python
- # Updating class variables in class methods
- # Updating class variables directly on the class
- # Updating instance variables
- # Updating a class variable is reflected in all instances
- # Accessing a class variable from an instance of the class
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)) #
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)
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)
mappingproxy('__dict__'
: '__dict__' of 'HtmlDocument' objects>, '__doc__': None, '__module__': '__main__', '__weakref__': '__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)
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)
mappingproxy('__dict__'
: '__dict__' of 'HtmlDocument' objects>, '__doc__': None, '__module__': '__main__', '__weakref__': '__weakref__' of 'HtmlDocument' objects>, 'extension': 'html', 'render': 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 a 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.
Python access to class variables
Last updated: Feb 21, 2023
Reading time · 5 min
# Table of Contents
# Updating class variables in Python
Update class variables by accessing them directly on the class.
Class variables are shared by all instances and can be updated directly on the class or in a class method.
Copied!class Employee(): # 👇️ class variable cls_id = 'employee' def __init__(self, name, salary): # 👇️ instance variables self.name = name self.salary = salary # ✅ update class variable @classmethod def set_cls_id(cls, new_cls_id): cls.cls_id = new_cls_id return cls.cls_id # ✅ update instance variable def set_name(self, new_name): self.name = new_name return new_name print(Employee.cls_id) # 👉️ employee Employee.set_cls_id('new_employee_id') print(Employee.cls_id) # 👉️ new_employee_id bob = Employee('Bobbyhadz', 100) bob.set_name('Bobbyhadz2') print(bob.name) # 👉️ Bobbyhadz2
The class has a cls_id class variable and name and salary instance variables.
Class variables are shared by all instances and can be accessed directly on the class, e.g. Employee.cls_id .
Instance variables are unique to each instance you create by instantiating the class.
# Updating class variables in class methods
We used a class method to update the cls_id variable.
Copied!@classmethod def set_cls_id(cls, new_cls_id): cls.cls_id = new_cls_id return cls.cls_id
Class methods get passed the class as the first argument.
# Updating class variables directly on the class
Note that you can also set class variables directly on the class, e.g. Employee.cls_id = new_cls_id .
Copied!class Employee(): # 👇️ class variable cls_id = 'employee' def __init__(self, name, salary): # 👇️ instance variables self.name = name self.salary = salary print(Employee.cls_id) # 👉️ employee # ✅ update class variable Employee.cls_id = 'new_employee_id' print(Employee.cls_id) # 👉️ new_employee_id
Class variables are shared by all instances of the class, whereas instance variables are unique to each instance.
# Updating instance variables
You’ll more often have to update instance variables in the class. Here is an example.
Copied!class Employee(): # 👇️ class variable cls_id = 'employee' def __init__(self, name, salary): # 👇️ instance variables self.name = name self.salary = salary # ✅ update instance variable def set_name(self, new_name): self.name = new_name return new_name alice = Employee('Alice', 150) bob = Employee('Bobbyhadz', 100) bob.set_name('Bobbyhadz2') print(bob.name) # 👉️ Bobbyhadz2 print(alice.name) # 👉️ Alice
Updating one instance variable doesn’t update the attribute for the other instances.
# Updating a class variable is reflected in all instances
On the other hand, when you update a class variable, the value is updated for all instances.
Copied!class Employee(): # 👇️ class variable cls_id = 'employee' def __init__(self, name, salary): # 👇️ instance variables self.name = name self.salary = salary alice = Employee('Alice', 150) bob = Employee('Bobbyhadz', 100) print(bob.cls_id) # 👉️ employee Employee.cls_id = 'NEW_ID' print(alice.cls_id) # 👉️ NEW_ID print(bob.cls_id) # 👉️ NEW_ID
Updating the cls_id class variable is reflected in all instances.
# Accessing a class variable from an instance of the class
You can use the type() class if you need to access a class variable from an instance of the class.
Copied!class Employee(): cls_id = 'employee' def __init__(self, name, salary): self.name = name self.salary = salary bob = Employee('Bobbyhadz', 100) # 👇️ override class variable on the instance bob.cls_id = 'new' print(bob.cls_id) # 👉️ new # 👇️ access the actual class variable from the instance result = type(bob).cls_id print(result) # 👉️ employee
The instance overrides the cls_id variable, so to access the actual class variable, we had to use the type() class.
The type class returns the type of an object.