How do we access class attributes using dot operator in Python?

A class attribute is an attribute of the class rather than an attribute of an instance of the class. In Python, we can access class attributes using the dot operator (.) both through the class itself and through its instances.

In the code below, class_var is a class attribute, and i_var is an instance attribute. All instances of the class have access to class_var, which can also be accessed as a property of the class itself ?

Example

class MyClass(object):
    class_var = 2

    def __init__(self, i_var):
        self.i_var = i_var

foo = MyClass(3)
baz = MyClass(4)
print(foo.class_var, foo.i_var)
print(baz.class_var, baz.i_var)

The output of the above code is ?

2 3
2 4

Accessing Class Attributes Directly from Class

You can also access class attributes directly using the class name without creating an instance ?

class MyClass(object):
    class_var = 2

    def __init__(self, i_var):
        self.i_var = i_var

# Access class attribute directly
print("Class attribute:", MyClass.class_var)

# Create instance and access through instance
instance = MyClass(5)
print("Through instance:", instance.class_var)
Class attribute: 2
Through instance: 2

Modifying Class Attributes

When you modify a class attribute through the class name, it affects all instances. However, if you modify it through an instance, it creates an instance attribute that shadows the class attribute ?

class MyClass(object):
    class_var = 2

    def __init__(self, i_var):
        self.i_var = i_var

obj1 = MyClass(1)
obj2 = MyClass(2)

print("Before modification:")
print(f"obj1.class_var: {obj1.class_var}")
print(f"obj2.class_var: {obj2.class_var}")

# Modify through class - affects all instances
MyClass.class_var = 10
print("\nAfter modifying through class:")
print(f"obj1.class_var: {obj1.class_var}")
print(f"obj2.class_var: {obj2.class_var}")

# Modify through instance - creates instance attribute
obj1.class_var = 20
print("\nAfter modifying through obj1:")
print(f"obj1.class_var: {obj1.class_var}")
print(f"obj2.class_var: {obj2.class_var}")
print(f"MyClass.class_var: {MyClass.class_var}")
Before modification:
obj1.class_var: 2
obj2.class_var: 2

After modifying through class:
obj1.class_var: 10
obj2.class_var: 10

After modifying through obj1:
obj1.class_var: 20
obj2.class_var: 10
MyClass.class_var: 10

Conclusion

Use the dot operator to access class attributes through both the class name and instances. Remember that modifying through the class affects all instances, while modifying through an instance creates a shadowing instance attribute.

Updated on: 2026-03-24T19:40:28+05:30

793 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements