为什么将Python整数实现为对象? [英] Why are Python integers implemented as objects?

查看:137
本文介绍了为什么将Python整数实现为对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么将Python整数实现为对象?

Why are Python integers implemented as objects?

文章为什么Python变慢:在引擎盖下及其注释包含有关Python内存模型及其后果的有用信息,尤其是对性能的影响.

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.

特别是,将Python称为动态类型并不是答案.可以使用动态类型的语言将整数实现为整数.

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.

推荐答案

"Python是一种动态类型的语言"是答案之一.要知道的另一件事:python的int与大多数其他语言中得到的整数不同. Python int实际上支持长算术(即可以容纳大于2 ^ 64的值).速度较慢,这是不可避免的,但它为您提供了更多的灵活性.

"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.

至于怪异"行为:请勿在python中使用is来比较值. python is所做的是检查,两个变量指向完全相同的对象.通过比较其ID来做到这一点.这不是您大多数时候想要的.作为经验法则-仅使用is检查is None而不是其他任何内容.

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.

这篇关于为什么将Python整数实现为对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆