Python将什么当作参考类型? [英] What does Python treat as reference types?

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

问题描述

我认为Python中的序列类型是值类型.事实证明它们是引用类型(意味着变量的值在分配给新变量时不会被复制,而是被引用).所以现在我想知道,Python中的值类型是什么?也就是说,我可以在Python中为新变量分配什么类型,而不必担心变量被引用了?

I assumed sequence types in Python were value types. It turns out they're reference types (Meaning that the value of a variable won't be copied when assigned to a new variable, but referenced). So now I'm wondering, what are the value types in Python? That is, what types in Python can I assign to new variables without worrying that the variable was referenced?

推荐答案

所有值都是引用.您需要担心的是类型是否为可变.基本的数字和字符串类型以及tuplefrozenset是不可变的.绑定到其中一种类型的对象的名称只能被反弹,而不能被突变.

All values in Python are references. What you need to worry about is if a type is mutable. The basic numeric and string types, as well as tuple and frozenset are immutable; names that are bound to an object of one of those types can only be rebound, not mutated.

>>> t = 1, 2, 3
>>> t[1] = 42
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

这篇关于Python将什么当作参考类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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