问题
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
回答1:
You should replace last line with:
print(int(5) == int(6))
to force/ask Python to use your new class for integer numbers.
回答2:
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.
来源:https://stackoverflow.com/questions/44204937/is-there-any-way-to-override-pythons-built-in-class