object types, mutable or not?
MRAB
python at mrabarnett.plus.com
Sun May 13 19:12:46 EDT 2018
On 2018-05-13 21:02, Mike McClain wrote:
> I'm new to Python and OOP.
> Python en 2.7.14 Documentation The Python Language Reference
> 3. Data model
> 3.1. Objects, values and types
> An object's type is also unchangeable. [1]
> [1] It is possible in some cases to change an object's type,
> under certain controlled conditions.
>
> It appears to me as if an object's type is totally mutable and
> solely dependant on assignment.
>
>>>> obj = 'a1b2'
>>>> obj
> 'a1b2'
>>>> type (obj)
> <type 'str'>
>>>>
>>>> obj = list(obj)
>>>> obj
> ['a', '1', 'b', '2']
>>>> type (obj)
> <type 'list'>
>>>>
>>>> obj = dict( zip(obj[0::2],obj[1::2]) )
>>>> type (obj)
> <type 'dict'>
>>>> obj
> {'a': '1', 'b': '2'}
>
> At what level does my understanding break down?
>
You're not mutating an object, you're creating new objects and then
binding them to the same name.
The name 'obj' refers to a string, then a list, etc.
BTW, you should be using Python 3 unless you really need Python 2.
Python 2.7 is the last in the Python 2 line, and it'll not longer be
supported after 2020.
More information about the Python-list
mailing list