DEV Community

Cover image for Python: Inheritance, File System, Error Handling 🎯
Killian Frappart
Killian Frappart

Posted on

Python: Inheritance, File System, Error Handling 🎯

Another week of Python has passed and once again, there are a lot of new topics to write about!

Every hour spent learning make me realize how powerful and complex this language is.

Let's dive in πŸŠβ€β™‚οΈ

Table of Contents


Inheritance is a key aspect of the object-oriented programming paradigm.

In the last post, I introduced classes with a simple example. The idea here, is to create a "child" class that inherits from its "parent" class.

A child class has access to public attributes and methods of its parents.

# Parent Class
class Vehicle:
    def __init__(self, color):
        self.color = color

    def info(self):
        print(f"Vehicle => color: {self.color}")

vehicle = Vehicle("red")  # Vehicle => color: red

# Child Classes
class Car(Vehicle):
    def __init__(self, color, brand):
        self.brand = brand
        self.wheels_count = 4

    def info(self):
        print(f"Car => color: {self.color} - brand: {self.brand} - wheels count: {self.wheels_count}")

class Bike(Vehicle):
    def __init__(self, color, brand):
        self.brand = brand
        self.wheels_count = 2

    def info(self):
        print(f"Bike => color: {self.color} - brand: {self.brand} - wheels count: {self.wheels_count}")

car = Car("blue", "Ferrari")  # Car => color: blue - brand: Ferrari - wheels count: 4

bike = Bike("Yellow", "Yamaha")  # Bike => color: Yellow - brand: Yamaha - wheels count: 2
Enter fullscreen mode Exit fullscreen mode

In the example above, we declare "Car" and "Bike" classes that derives from the "Vehicle" class. They both have access to "Vehicle"'s constructor (init) and the info() method.

Here I decided to override the constructor to add one more field and adapt the info method's behavior.

NOTE: The "super" keyword simply refer to the parent class.

Error Handling

We are used to errors and programs wipe out as developers but if possible, you should ship a rock-solid, error-proof and bug free program to production.

From now, I assume that your Python code is correct and does not raise syntax error.

If you run an unhandled exception, the program will probably crash and stop the execution straight away.

In order to avoid potential crashes, it is recommended to wrap error-prone code in a "try-except-else" block.

try except else

    # Code to execute
    raise Exception("An error occured.")  # Some code raise an exception.
    # If there is an exception
    print("Something failed ❌")
    # If no exception was raised
    print("Everything is Ok βœ…")
    # Code to execute
    print("We made it πŸ‘")
Enter fullscreen mode Exit fullscreen mode

It ain't much, but it is enough to start working on your code's quality. Of course, it would not be a good practice to wrap your whole codebase in a massive try block...

File System

Python offers a simple way to interact with local files and directories.

The best practice for opening and closing files uses the with keyword. This keyword closes the file automatically after the nested code block completes.

# text.txt

with open("text.txt", "r") as file:
    print( # Display "Hello" in the console.

with open("text.txt", "a") as file:
    file.write(" World!") # file.txt's content is "Hello World!" now.

with open("text.txt", "w") as file:
    file.write("Cool!") # file.txt's content is "Cool!" now.
Enter fullscreen mode Exit fullscreen mode

The first argument is the target file and the second is the opening mode.


It is also possible to interact with directories using "os" methods. The example below shows how to list every files in the current directory.

import os

with os.scandir("./") as entries:
    for entry in entries:

# Displays in the console: 
# file.txt
# .vscode
Enter fullscreen mode Exit fullscreen mode

Another interesting method is "mkdir" that creates a new directory.

import os

    print("Directory already exists.")
    print("Directory created βœ…")
Enter fullscreen mode Exit fullscreen mode

Here, it might be clever to wrap your code in a "try-except" block because the program will crash if a directory with the same name already exists.

thank you for reading πŸ˜‡

Top comments (0)