Adding Arbitrary Attributes
Arbitrary attributes refer to the ability to assign custom properties to objects. These properties are not predefined within the class blueprint; instead, we can create them based on our specific needs. Think of arbitrary attributes as labels we can attach to objects to describe unique features that aren't part of the original class definition. This flexibility allows us to tailor each instance to our requirements without altering the original class structure.
Imagine you have a class, just like our Coffee example:
class Coffee:
pass
Now, let's say we've created an instance of the class called drink:
drink = Coffee()
At this point, the drink object doesn't have any properties or attributes beyond what the Coffee class blueprint defines. However, with arbitrary attributes, we can go beyond the class blueprint and add new properties that are unique to this specific instance.
For instance, consider the lines of code below:
drink.name = "Latte"
drink.calories = 200
In these lines, we're attaching two arbitrary attributes to the drink object: name and calories. These attributes are not predefined within the Coffee class, but we can effortlessly introduce them to suit our needs.
To put it simply, arbitrary attributes act like labels we can stick onto objects to describe specific characteristics that weren't initially part of the original class design. In the example above, we're labeling the drink object with a name ("Latte
") and a calorie count (200
).
The beauty of this feature lies in its flexibility. It enables us to customize each instance of a class without altering the class blueprint itself. This means that we can tailor objects to our exact requirements without affecting the core structure of the class. It's like adding personalized stickers to a standard product, enhancing its uniqueness while keeping the original design intact.
Here is the complete code:
class Coffee:
pass
drink = Coffee()
drink.name = "Latte"
drink.calories = 200
print(drink.name, drink.calories)