Is it possible to replace some built-in python types with custom ones?
I want to create something like:
class MyInt(object):
...
__builtin__.int = MyInt
x = 5
You seem to be asking if it's possible to override the type that is created when you enter literals. The answer is no. You cannot make it so that x = 5
uses a type other than the built-in int
type.
You can override __builtin__.int
, but that will only affect explicit use of the name int
, e.g., when you do int("5")
. There's little point to doing this; it's better to just use your regular class and do MyInt("5")
.
More importantly, you can provide operator overloading on your classes so that, for instance, MyInt(5) + 5
works and returns another MyInt. You'd do this by writing an __add__
method for your MyInt class (along with __sub__
for subtraction, etc.).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With