Attributes

Understanding Attributes

In Python, when we say “attribute”, we refer to any name following a dot after an instance of a class. For example, when we say object.attribute, ‘attribute’ is an attribute of the class instance ‘object’. They hold data pertaining to an instance and define the characteristics of an object.

Declaring Attributes

Attributes are typically declared within the class definition. However, they can also be dynamically added to an instance after the instance has been created. Check the code below:

 1class Robot:
 2    def __init__(self, name, color):
 3        self.name = name            # adding attribute 'name'
 4        self.color = color          # adding attribute 'color'
 5
 6r1 = Robot('Beepo', 'yellow')
 7
 8# Dynamically adding attribute 'height'
 9r1.height = 16
10print(r1.height)   # Output: 16

Accessing Attributes

Attributes can be accessed using the dot operator on an instance of the class.

1r2 = Robot('Rob', 'red')
2print(r2.name)   # Output: Rob
3print(r2.color)  # Output: red

Modifying Attributes

Similar to accessing, modifying an attribute can be done using the dot operator.

1r3 = Robot('Spark', 'blue')
2print(r3.name)   # Output: Spark
3
4r3.name = 'Bolt'
5print(r3.name)   # Output: Bolt

Here, we initially declared the robot’s name as ‘Spark’ and then changed it to ‘Bolt’.

Note

In Python, attributes declared within a method are local to that method and aren’t accessible outside that method. To make attributes accessible throughout the class instances, they are usually declared within the __init__ method. The self keyword refers to the instance of the class and is used to define and access attributes.