问题
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