Why are Python integers implemented as objects?

半腔热情 提交于 2020-06-17 15:51:25

问题


Why are Python integers implemented as objects?

The article Why Python is Slow: Looking Under the Hood as well as its comments contain useful information about the Python memory model and its ramifications, in particular wrt to performance.

But this article does not ask or answer the question why the decision to implement integers as objects was made in the first place.

In particular, referring to Python as dynamically typed is not an answer. It is possible to implement integers as integers in a dynamically typed language.


回答1:


"Python being a dynamically typed language" is one of the answers. Another thing to know: python's int is not the same integer you will get in most other languages. Python int actually supports long arithmetics (i.e. can hold values bigger than 2^64). It is slower which is unavoidable yet it gives you some additional flexibility.

As for the "weird" behavior: don't use is in python in order to compare values. What python is does is checks, that two variables point to the exact same object. It does so by comparing their ids. This is not what you want most of the time. As the rule of thumb - use is only to check for is None and nothing else.



来源:https://stackoverflow.com/questions/62236683/why-are-python-integers-implemented-as-objects

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