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
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 = 5uses a type other than the built-ininttype.You can override
__builtin__.int, but that will only affect explicit use of the nameint, e.g., when you doint("5"). There’s little point to doing this; it’s better to just use your regular class and doMyInt("5").More importantly, you can provide operator overloading on your classes so that, for instance,
MyInt(5) + 5works and returns another MyInt. You’d do this by writing an__add__method for your MyInt class (along with__sub__for subtraction, etc.).