Mia
Mia

Reputation: 2676

Is there any way to override Python's built-in class?

I am trying to change the behavior of python's int class, but I'm not sure if it can be done using pure python. Here is what I tried so far:

import builtins
class int_new(builtins.int):
    def __eq__(self, other):
        return True
int = int_new
print(5 == 6) # the result is False, but I'm anticipating True

Upvotes: 3

Views: 1260

Answers (2)

Mia
Mia

Reputation: 2676

A year later I finally learned what I was wondering. When I was learning Python, I was not exposed to the idea of what a primitive type is. After learning C++ I realized that I was actually wondering if it is possible to replace primitive type with other custom types. The answer is obviously no.

Upvotes: -2

davidedb
davidedb

Reputation: 876

You should replace last line with:

print(int(5) == int(6))

to force/ask Python to use your new class for integer numbers.

Upvotes: 2

Related Questions