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
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.info() # Vehicle => color: red
# Child Classes
class Car(Vehicle):
def __init__(self, color, brand):
super().__init__(color)
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):
super().__init__(color)
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.info() # Car => color: blue - brand: Ferrari - wheels count: 4
bike = Bike("Yellow", "Yamaha")
bike.info() # Bike => color: Yellow - brand: Yamaha - wheels count: 2
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:
# Code to execute
raise Exception("An error occured.") # Some code raise an exception.
except:
# If there is an exception
print("Something failed β")
else:
# If no exception was raised
print("Everything is Ok β
")
finally:
# Code to execute
print("We made it π")
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
Hello
# main.py
with open("text.txt", "r") as file:
print(file.read()) # 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.
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.
# main.py
import os
with os.scandir("./") as entries:
for entry in entries:
print(entry.name)
# Displays in the console:
# file.txt
# main.py
# .vscode
Another interesting method is "mkdir" that creates a new directory.
# main.py
import os
try:
os.mkdir("Test")
except:
print("Directory already exists.")
else:
print("Directory created β
")
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)