This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 3: Classes and attributes

Dictionaries revisited

face Josiah Wang

Back in Lesson 7, you have represented the structure of an object using dict, with various object attributes as keys to the dictionary.

person = {"id": "00-01-30", "name": "Ali", "age": 23, 
           "occupation": "student", "nationality": "uk"}

if person["id"] == "00-01-03":
    print(person["name"])
    print(person["nationality"])

Such dict structures provide a higher level abstraction over simple data types, allowing you to represent an entity as a single unit.

In your mind, however, you will likely still be thinking that person is a dict with some keys and values.

Can we go one step further and provide yet another level of abstraction, so that when you read your code, you will think of person as a Person, rather than a dict?

For example, try reading the code below. Does it feel easier and even more natural to read than the version above?

person = Person(id="00-01-30", name="Ali", age=23, 
                occupation="student", nationality="uk")

if person.id == "00-01-03":
    print(person.name)
    print(person.nationality)

You might have even visualised the person in your mind, and read the code as “person is a Person named Ali with id 00-01-30, etc., and if the person’s id is 00-11-03, then print the person’s name and the person’s nationality.”

Such code is arguably easier to read and write, since you are modelling some concrete object/entity that you can imagine in your mind, rather than something more abstract and generic like a variable or a dict.

Another issue with dict is that it will be difficult to enforce that a person must have a name or a nationality. You might end up with cases where the dict has no keys for name or nationality. Then what happens? Would it not be nice if you can easily be more consistent, and can pre-define what attribute a person must have, so that you can easily remember (or be enforced) to provide this when coding?

In this chapter, you will build on these ideas, and create your own complex data type such as for a Person above. You can then create objects out of your custom data type and use them!