Member-only story
A simple way to have many class constructors in Python
Something missing in Python, which you may be envious of if you are coming from programming languages like C++ or Crystal, is the ability to overload a function or method, especially a class constructor which is the focus of this article. I will show you a simple and elegant way to overcome this issue and avoid a pitfall I see in some code around.
For our example, we will consider a simple Point class that will be a representation of a vector in two dimensions. It can be instantiated in three different ways:
- Pass the two coordinates x and y directly
- Pass an array of values
- Pass a dict (or map in C++ jargon)
Here is what it can look at in C++. Honestly, my C++ is rusty, so I asked ChatGPT to help me with this part. 🫣
#include <iostream>
#include <vector>
#include <map>
using namespace std;
class Point {
private:
int x;
int y;
public:
// Constructor with two separate parameters for x and y
Point(int x, int y) {
this->x = x;
this->y = y;
}
// Constructor with a vector having x and y
Point(vector<int> vec) {
if (vec.size() != 2) {
throw invalid_argument("The vector should have only two elements represeting x and y coordinates.");
}
x =…