Accessing Object Attributes in a Python Class Using Format
While the format() method is commonly used for string formatting, it also offers some other practical uses.
For example, it allows you to access and display the values of an object's attributes within a Python class.
A Practical Example
Let's create a simple class called Capital.
This class has just one attribute, city.
- class Capital:
- def __init__(self, city):
- self.city = city
- Italy = Capital(city="Rome")
- France = Capital(city="Paris")
In lines 4 and 5, I create two instances of the Capital class, named Italy and France.
Each instance is assigned the name of the respective capital city.
To retrieve the value of the city attribute for the Italy object, you can write:
print("The capital of Italy is {Capital.city}".format(Capital=Italy))
Within the string, the placeholder refers to the attribute Capital.city.
The format() function tells Python which object to use (Italy in this case).
The output will be:
The capital of Italy is Rome
And you can do the same for other instances.