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:
Accessing Attributes
Attributes can be accessed using the dot operator on an instance of the class.
Modifying Attributes
Similar to accessing, modifying an attribute can be done using the dot operator.
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.