One major reason why most programmers find it hard to adapt to new programming languages is that they’re stuck in their current programming language perspective or viewpoint. You probably heard the saying “if the only tool you have is a hammer, then every problem looks like nails to you” (or something like that) — and that’s exactly what prevents them from learning other tools or language, and I’ve proven this many, many times; so today, I’m going to share with you what a conversation with me goes like when discussing this aspect or concept.
Understand the concept first, not the details
Most programming languages share common concepts and only differs in their implementation details. That’s why if you try to find a detail from language A within language B, you’re likely not gonna find it. But if you look for the concept behind that detail, you’ll likely find it.
How to teach OOP in Python from a SQL perspective
One of the struggles in programming is how to understand and implement OOP (Object Oriented Programming) on any language. Today I’ll show you how you can do this in Python if you’re coming from a SQL background or if you are teaching someone that knows SQL but wants to learn Python.
CREATE TABLE: SQL
Let’s start with a simple SQL for defining a table of Employees. SQL developers would be very familiar with this:
Now, think of classes as tables.
Lightbulb moment yes? 🙂
Here’s how you can implement this as a Python class:
NOTE that I’m using a Python package dataclasses
to make the code super simple and have it build the boiler plates for me.
Okay, let’s add another table called Attendance. First, in SQL then as a Python class.
NOTE: I’m going for the simplest approach possible. We could use descriptors just like Django, but you won’t do that for someone that barely knows Python. 🙂
Now that we’ve defined the table structure, let’s represent an in-memory table rows for each of them (using Python list):
INSERT RECORDS
Now, let’s translate our knowledge of SQL for creating a record and inserting that to the table.
Below are the lines that represent SQL (commented) and how we can represent the same concept in Python:
You may also use the insert
method of a list, if you really want the words closely match that of SQL.
SELECT RECORDS
Here’s a comparison for selecting records for both SQL and Python:
UPDATE RECORDS
Updating a Python class is either updating the property directly or via a class method. The Python code below is an over simplification of how a SQL engine “might” do it.
NOW IT’S YOUR TURN
Try implementing a DELETE SQL statement in terms of Python code. See if this analogy and shift in perspective would help you adapt to a new language — or not (in that case, write a comment and tell me about it.)