Using format() to Access Instance Attributes in Python
Most Python programmers use the format() method to insert values into strings. However, many beginners do not realize that it can also access an object's attributes directly within a format string.
This feature makes it easy to display information stored in the instances of a Python class without having to extract the attribute values beforehand.
A Practical Example
Suppose you create a simple class called Capital.
The class contains a single instance attribute named city.
- class Capital:
- def __init__(self, city):
- self.city = city
- Italy = Capital(city="Rome")
- France = Capital(city="Paris")
In lines 4 and 5, two objects are created from the Capital class: Italy and France.
Each object stores the name of a capital city in its city attribute.
To display the capital of Italy, you can write:
print("The capital of Italy is {country.city}".format(country=Italy))
The placeholder {country.city} tells Python to access the city attribute of the object associated with the name country.
When the format() method is executed, the keyword argument country is linked to the Italy object. Python then retrieves the value of country.city and inserts it into the string.
The result is:
The capital of Italy is Rome
This technique is not limited to the Italy object. You can use the same syntax with any instance of the class, making format() a simple and readable way to include object attributes in your output.
Although f-strings are generally preferred in modern Python code, understanding how attribute access works with format() can help you read and maintain older codebases where this method is still widely used.
