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

限于喜欢 提交于 2019-12-11 01:46:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!