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 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 −


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)


This gives the output

(2, 3)
(2, 4)

Updated on: 20-Feb-2020


Kickstart Your Career

Get certified by completing the course

Get Started