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

PythonServer Side ProgrammingProgramming

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 −

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)

Output

This gives the output

(2, 3)
(2, 4)
raja
Published on 16-Jan-2018 10:18:23
Advertisements