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