What can you gain from switching from dictionaries to objects?
This is a pretty vast question.
It is right, in Python, that an object is semantically equivalent to a dictionary, since an object is almost equivalent to its __dict__
attribute (I will not detail this "almost" here, since it is far off the topic).
I see two main benefits from using classes instead of dictionaries: abstraction, and comfort.
Abstraction
When you are in the design phase, especially for short to medium length programs, you generally want to write the skeleton of your code while thinking.
In a situation where you need to model interactions, it's more natural to think in classes, because it's halfway between speaking and programming.
This makes it easier to understand your own problematic. In addition, it greatly improves the readability of your code, because it seems natural, even when the reader does not know anything about your code.
This brings you concepts such as inheritance and polymorphism, that enrich the abstraction offered by OOP.
Comfort
One of Python's many strengths is its data model. The plenty magic methods and attributes allow you to use very simple syntaxes. In addition, it can take care of some operations in your place.
Here are some comparisons between imperative and object-oriented programming in Python.
Of course, everything in Python is an object, so I will use dot calls (foo.bar()
) even in imperative examples.
Files reading
Imperative way
f1 = open(in_path, 'r')
f2 = open(out_path, 'w')
for line in f1:
processed = process(line)
f2.write(processed)
# Oops, I forgot to close my files...
Object-oriented way
with open(in_path, 'r') as f1, open(out_path, 'w') as f2:
for line in f1:
processed = process(line)
f2.write(processed)
# I don't have to close my files, Python did it for me
Note that for line in f
is an extensive use of Python's object-oriented data model. Imagine the pain if this syntax did not exist (well, just try it in C).
Emptiness test
Imperative way
if len(some_list) == 0:
print("empty list")
Object-oriented way
if some_list:
print("empty list")
Iteration over a sequence
Imperative way
i = 0
while i < len(some_sequence):
print(some_sequence[i])
i += 1
Object-oriented way
for elt in some_sequence:
print(elt)
But the actual strength of this data model is that it lets you redefine a lot of magic attributes. For instance, you can make complex things comparable just by implementing __lt__
, __le__
and so on, which will redefine the behaviour of <
, <=
, and so on. Thenceforth, built-in functions like min
, max
or sort
will understand how to compare your objects.
This said, the use of mere dictionaries can be more than enough in a large variety of cases.
And at the end of the day, OOP is only one paradigm, and imperative programming just works as fine.