Access class variables from an instance in Python

avatar

Borislav Hadzhiev

Last updated: Sep 14, 2022

banner

Photo from Unsplash

Access class variables from an instance in Python #

Use the type() class to access a class variable from an instance, e.g. type(instance).cls_id. When an instance is passed to the type() class, it returns a reference to the class, on which you can access class variables.

main.py
class Employee(): cls_id = 'employee' def __init__(self, name, salary): self.name = name self.salary = salary def get_name(self): print(Employee.cls_id) print(type(self).cls_id) return self.name bob = Employee('Bobbyhadz', 100) print(type(bob).cls_id) # 👉️ employee

We used the type() class to access class variables from an instance.

The type class returns the type of an object.

You can also use the type() class if you need to access a class variable inside of a method.

This is useful because an instance might override the value of a class variable.

main.py
class Employee(): cls_id = 'employee' def __init__(self, name, salary): self.name = name self.salary = salary def get_name(self): print(Employee.cls_id) print(type(self).cls_id) return self.name bob = Employee('Bobbyhadz', 100) # 👇️ override value of class variable bob.cls_id = 'bobbyhadz' print(bob.cls_id) # 👉️ bobbyhadz # 👇️ still have access to actual class variable print(type(bob).cls_id) # 👉️ employee

The instance overrides the value of the cls_id class variable, but can still access it using the type() class.

Most commonly the return value of the type() class is the same as accessing the __class__ attribute on the object.

The following code sample uses the __class__ attribute to access a class variable from an instance of the class.

main.py
class Employee(): cls_id = 'employee' def __init__(self, name, salary): self.name = name self.salary = salary def get_name(self): print(Employee.cls_id) print(type(self).cls_id) return self.name bob = Employee('Bobbyhadz', 100) bob.cls_id = 'bobbyhadz' print(bob.cls_id) # 👉️ bobbyhadz print(bob.__class__.cls_id) # 👉️ employee

Which approach you pick is a matter of personal preference.

The type() class is more elegant because we don't have to access attributes prefixed with two underscores, but the __class__ attribute is more explicit.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.