What does Python treat as reference types?

放肆的年华 提交于 2019-11-26 17:28:50

问题


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?


回答1:


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



回答2:


The answer above is correct, but I object to the semantics of "reference".

C-like languages treat variables as fixed buckets, in which values are placed. When you call a function, a new set of buckets are created, and the values are copied into them. Sometimes, a bucket is pass-by-reference, and actually becomes an alias for the caller's bucket.

Python, on the other hand, treats variables as mere labels (names) for values (objects). When you call a function, a new set of labels are created and slapped onto those same objects.

It doesn't make sense to mention "references" in the context of Python, because in every other language, "reference" implies an alternative to "value". Python has no such duality; it just passes around and assigns objects. Nothing is referred to.

Nitpicky, perhaps, but the terminology causes no end of confusion for C++ programmers, who e.g. hear Python passes by references and don't understand how to reassign the caller's names.



来源:https://stackoverflow.com/questions/6158907/what-does-python-treat-as-reference-types

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