Great timing! Last week I was trying to emulate a certain Rust example in Python.
Rust has a way to implement families of classes without subclassing,
which I think could be a great addition to Python someday. I'll explain below.
Here is a Rust example (
https://youtu.be/WDkv2cKOxx0?t=3795)
that demonstrates a way to implement classes without subclassing.
# Rust Code
enum Shape {
Circle(f32),
Square(f32),
Rectangle(f32, f32)
}
impl Shape {
fn area(self) -> f32 {
match self {
Shape::Circle(r) => 3.1 * r * r,
Shape::Square(l) => l * l,
Shape::Rectangle(l, w) => l * w
}
}
}
fn main () {
let c = Shape::Circle(3.0);
let s = Shape::Square(3.0);
let r = Shape::Rectangle(3.0, 7.5);
println!("○ {}", c.area());
println!("□ {}", s.area());
println!("▭ {}", r.area());
}
# Output
○ 27.899998
□ 9
▭ 22.5
The general idea is:
- declare classes that share a certain type
- extend common methods with a match-case style
That's it. No sub-classing required.
I wondered if someday, can we do this in Python? This match-case proposal seems to fit well in this example.
While I know this PEP does not focus on detailed applications,
does anyone believe we can achieve elegant class creation (sans subclassing) with match-cases?