Newbie look at Python and OO

jmg3000 at gmail.com jmg3000 at gmail.com
Thu May 10 12:45:44 EDT 2007


On May 10, 11:58 am, walterbyrd <walterb... at iname.com> wrote:
>[snip]
>
> 2) list assignment handling, pointing two vars to the same list:
>
> With simple data types:>>> a = 5
> >>> b = a
> >>> a = 3
> >>> a,b
>
> (3, 5)
>
> Which is what I'd expect, since I have changed a, but not b.
>
> But with lists:>>> a = list("1234")
> >>> b = a
> >>> a.append("5")
> >>> a,b
>
> (['1', '2', '3', '4', '5'], ['1', '2', '3', '4', '5'])
>
> b  changes even though I have not touched b. I know why, but this is
> not what I would ordinarilly expect, it does not seem intuitive.

Well, although it may not be what you expect right now, it *is* quite
uniform with the rest of the language. That is: labels refer to
objects. Writing ``a = b`` just makes the 'b' label refer to the same
thing that the 'a' label refers to. Nice and simple.

> And,
> IMO, it gets worse:
>
> >>> a = list("1234")
> >>> b = a
> >>> a = a + ['5']
> >>> a,b
>
> (['1', '2', '3', '4', '5'], ['1', '2', '3', '4'])

Now here, after you've set 'a' and 'b' to refer to the same object,
you went and created a new object (a + ['5']) for a to refer to. ``a +
['5']`` creates a new object, whereas ``a.append('5')`` just modifies
the existing object. (By the way, as an aside, '5' is a one-character
string, not a number.)

> [snip]
>
> 3) ambiguous use of the form: this.that()
>
> Sometimes, this.that() means module.funcion() as in:
>
> >>> os.dirlist(".")
>
> Other times, "this" is sort of like a parameter to the "that"
> function:
>
> >>> a = list("1234")
> >>> "_".join(a)
>
> '1_2_3_4_5'

I think I see what you mean: In Python, there's this convention that
you're supposed to name your classes starting with a capital letter
(``class HeadCheese(object):``), but for core built-in classes, they
start with a lower-case letter (like ``list``, ``dict``, ``set``,
``file``, etc.). So, ``list('foo')`` is actually a constructor call.

Also, note that, in Python, "_" is a literal for creating a string
object, so you can call methods on that resulting object -- as in
``'_'.join('cheezit')`` -- the same as if you'd said ``foo = "_";
foo.join('cheezit')``.

> [snip]
>
> I'm not complaining. Python is a great language in many respects. But,
> I would take some issue with those claiming Python is intuitive and
> easy. IMO: there seems to be many ambiguous, unintuitve, and
> confusing, aspects to Python.

Well, every language has its warts. :) Folks are working to minimize
or remove a number of them for Python 3000.

---John




More information about the Python-list mailing list