Attributes
An attribute or field is a variable that is bound to an object. It is a property that describes the object. Attributes are defined in the class and are accessed using the dot notation.
How to create attributes
class Beam:
def __init__(self, length, width, height):
self.length = length
self.width = width
self.height = height
def calculate_volume(self):
volume = self.length * self.width * self.height
return volume
➔➔ Note that attributes are created with the .
and the name of the attribute
Access/modify attributes
Attributes can be then modified by assigning a new value to them. This is done by using the dot notation and the assignment operator =
.
# class instantiation
beam = Beam(10, 20, 30)
# accessing attributes
print(beam.length) # 10
print(beam.width) # 20
print(beam.height) # 30
# store the attribute in a new variable
length = beam.length
width = beam.width
height = beam.height
# modify the attribute
beam.length = 100
beam.width = 200
beam.height = 300
➔➔➔ *Attention: in reality in Python you can also add new attributes once the class is created:
beam = Beam(10, 20, 30)
beam.new_attribute = 100
Although it is considered bad practice, it is technically possible.