Python Basics

Declare Your First Python Class — Understand 3 Basic Components

Better organize your code using custom classes

Yong Cui
The Startup
Published in
7 min readMay 24, 2020

--

Photo by SpaceX on Unsplash

When our project’s scope grows, we’ll find it gradually tedious to manage data using built-in data types. For example, let’s say we’re building an employee management tool, and thus we’ll need to deal with data related to individual employees. Using the built-in dictionary data type, we’ll have to use the following data structure (i.e., dictionary) to refer to a particular employee.

>>> employee = {"name": "John Smith", "employee_id": 10997, "gender": "M"}

Say that we want to access this employee’s information, we’ll have to use the square brackets to retrieve particular values.

>>> employee["name"]
'John Smith'
>>> employee["gender"]
'M'
>>> employee["employe_id"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'employe_id'

It’s all good if we’re careful enough to spell the keys correctly. However, if we misspell the key, the corresponding value can’t be retrieved. Moreover, our program can even crash. Although many advanced Python editors, such as Visual Studio Code and PyCharm, have the intelligent code feature, they don’t always offer hints about the keys for dictionaries.

--

--

Yong Cui
The Startup

Work at the nexus of biomedicine, data science & mobile dev. Author of Python How-to by Manning (https://www.manning.com/books/python-how-to).