Modifying Class Object
John Posner
jjposner at optimum.net
Mon Feb 15 19:33:19 EST 2010
On 2/15/2010 6:09 PM, Steven D'Aprano wrote:
> On Mon, 15 Feb 2010 21:25:23 +0000, Arnaud Delobelle wrote:
>
>> John Posner<jjposner at optimum.net> writes: [...]
>>>> x = s[0]
>> [...]
>>> assigns the name *x* to the object that *s[0]* refers to
>>
>> s[0] does not refer to an object, it *is* an object (once evaluated of
>> course, otherwise it's just a Python expression).
>
> Precisely. Treated as an expression, that is, as a string being evaluated
> by the compiler, we would say that it *refers to* an object (unless
> evaluation fails, in which case it refers to nothing at all). But treated
> as whatever you get after the compiler is done with it, that is, post-
> evaluation, we would say that it *is* an object.
>
> This subtle distinction is essentially the difference between a label and
> the thing that is labeled.
Is this your only quibble with my writeup? If, so, I'm gratified. And
your objections make perfect sense. Still, I'll attempt to justify my
phrasing. I was originally going to write:
assigns the name *x* to the object that THE NAME *s[0]* refers to
... but I didn't want to start a distracting argument on the use of the
phrase *the name* to describe the 4-char string *s[0]*. So now I'll try
to (briefly) make my case.
Yes, it might be more correct to say that *s[0]* is an expression
(equivalent to the more obvious expression *s.__getitem__(0)*). But in
common usage, the 4-char string *s[0]* _behaves_ like a name. If you
accept this viewpoint, the story on Python assignment statements becomes
quite simple ...
Syntactic sugar aside, there are only two kinds of assignment statements:
1. NAME = EXPRESSION
The EXPRESSION creates a new object, and the NAME is assigned to that
object. Examples:
x = x + 1
obj = MyClass(1, 2, "red")
mywordlist = mysentence.split()
2. NAME2 = NAME1
No new object is created. NAME2 becomes another name (an "alias") for
the existing object that currently has NAME1 assigned to it. Examples:
y = x
s[0] = s[42]
mydict["spamwich"] == this_sandwich
obj.color = MYCOLORS.LTGREEN
This viewpoint might fail in advanced areas of Python programming:
properties/descriptors, double-underscore methods, etc. But in my own
day-to-day usage (admittedly, I'm a hobbyist Python programmer, not a
professional), it's never failed me to think this way:
* A dict is a collection of user-devised names, each of which
is assigned to an object.
* A list/tuple is an interpreter-maintained collection of integer
names (0, 1, 2, ...), each of which is assigned to an object.
* A class instance is very much like a dict.
Tx,
John
More information about the Python-list
mailing list