In , I can define a class Fraction to represent a rational number. I can then create one with Fraction(2, 3).

Is there a way to overload a construction operator so I can say something like 2 ./. 3 instead?

@peterdrake I don't think so, because the operator you'd have to override is actually multiple methods of the built-in number types (int and float and maybe complex), and I don't believe Python lets you change methods of built-in types. You can inherit from them and override the methods in your subclass, but then you have to use your subclass constructor to create the object in the first place, like MyNumber(2) / 3.

I guess there is a really obscure trick I can think of where you use a custom file encoding to intercept Python's reading of the source code and you can modify it before it gets parsed, e.g. to replace all numeric constants with calls to your subclass constructor, but that's kind of fragile and is more for entertainment value that for actual use in real code.

#Python

Sign in to participate in the conversation
Qoto Mastodon

QOTO: Question Others to Teach Ourselves
An inclusive, Academic Freedom, instance
All cultures welcome.
Hate speech and harassment strictly forbidden.